flutter ListView KeepAlive after some scroll

后端 未结 4 652
抹茶落季
抹茶落季 2020-12-11 18:37

I want to keepAlive my widgets which are already rendered in ListView. I was tried with addAutomaticKeepAlives:true properties which p

相关标签:
4条回答
  • 2020-12-11 18:59

    For automaticKeepAlive to work, each item that needs to be kept alive must send a specific notification.

    A typical way to fire such notification is using 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;
    }
    
    0 讨论(0)
  • 2020-12-11 19:00

    if you want to keep alive a list of slivers (for CustomScrollView) all you need to do is use the 'SliverChildListDelegate' instead of 'SliverChildBuilderDelegate'

    Here's my code:

    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,
            // ),
          ),
       ],
    );
    

    As you can see in the code, I was using SliverChildBuilderDelegate before

    0 讨论(0)
  • 2020-12-11 19:07

    As stated by AutomaticKeepAliveClientMixin and Remi's answer,

    Subclasses must implement wantKeepAlive, and their build methods must call super.build (the return value will always return null, and should be ignored).

    Therefore, change your build method to:

    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;
    }
    
    0 讨论(0)
  • 2020-12-11 19:07

    You can try looking at the cacheExtent property on listview builder as well. Setting that to a value to cover your items will keep them all alive. Thanks to Remi above. I had no idea the items needed keepAlive when using it on the list - that was not in the flutter doco previously...

    0 讨论(0)
提交回复
热议问题