滚动后颤振ListView KeepAlive

时间:2018-09-27 16:13:30

标签: listview flutter flutter-layout flutter-sliver

我想keepAlive我的小部件已经在ListView中呈现。我尝试使用addAutomaticKeepAlives:true类提供的ListView属性。

这是我使用的示例代码。由SliverChildBuilderDelegate提供的SliverList委托中存在相同的问题。

ListView.builder(
    itemBuilder: (context,index){
      return Card(
        child: Container(
          child: Image.asset("images/${index+1}.jpg",fit: BoxFit.cover,),
          height: 250.0,
        ),
      );
    },
    addAutomaticKeepAlives: true,
    itemCount:40 ,
);

4 个答案:

答案 0 :(得分:6)

要使automaticKeepAlive正常工作,需要保持活动的每个项目都必须发送特定的通知。

触发此类通知的一种典型方法是使用AutomaticKeepAliveClientMixin

class Foo extends StatefulWidget {
  @override
  FooState createState() {
    return new FooState();
  }
}

class FooState extends State<Foo> with AutomaticKeepAliveClientMixin {
  @override
  Widget build(BuildContext context) {
    return Container(

    );
  }

  @override
  bool get wantKeepAlive => true;
}

答案 1 :(得分:6)

如AutomaticKeepAliveClientMixin和Remi的回答所述,

子类必须实现wantKeepAlive,并且其构建方法必须 调用super.build(返回值将始终返回null,并且应该 被忽略)。

因此,将您的构建方法更改为:

class Foo extends StatefulWidget {
  @override
  FooState createState() {
    return new FooState();
  }
}

class FooState extends State<Foo> with AutomaticKeepAliveClientMixin {
  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Container(

    );
  }

  @override
  bool get wantKeepAlive => true;
}

答案 2 :(得分:2)

如果您想保留一个条子列表(对于CustomScrollView),您需要做的就是使用'SliverChildListDelegate'而不是'SliverChildBuilderDelegate'

这是我的代码:

final List<Product> products;
return CustomScrollView(
  controller: _scrollController,
    slivers: [
      _mySliverAppBar(context, title),
      SliverList(
        delegate: SliverChildListDelegate(
          List.generate(products.length, (index) => _myProductCard(context,products[index]))
        )
        // SliverChildBuilderDelegate(
        //   (context, index) => _myProductCard(context, products[index]),
        //   childCount: products.length,
        // ),
      ),
   ],
);

如您在代码中所见,我以前使用过SliverChildBuilderDelegate

答案 3 :(得分:1)

您也可以尝试在listview构建器上查看cacheExtent属性。将其设置为一个值以覆盖您的物品将使它们始终存活。 感谢上面的Remi。我不知道在列表上使用它时需要keepAlive的项目-以前不在flott doco中...