I want to keepAlive
my widgets which are already rendered in ListView
. I was tried with addAutomaticKeepAlives:true
properties which p
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;
}
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
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;
}
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...