addAutomaticKeepAlives property
Whether to wrap each child in an AutomaticKeepAlive.
Typically, lazily laid out children are wrapped in AutomaticKeepAlive widgets so that the children can use KeepAliveNotifications to preserve their state when they would otherwise be garbage collected off-screen.
This feature (and addRepaintBoundaries) must be disabled if the children are going to manually maintain their KeepAlive state. It may also be more efficient to disable this feature if it is known ahead of time that none of the children will ever try to keep themselves alive.
Defaults to true.
Normally, widgets in a lazily built list like ListView.builder are disposed of when they leave the visible area to maintain performance. This means that any state inside a StatefulWidget would be lost unless explicitly preserved.
In this example, each list item is a StatefulWidget that includes a counter and an increment button. To preserve the state of selected items (based on their index), the AutomaticKeepAlive widget and AutomaticKeepAliveClientMixin are used:
- The
wantKeepAlive
getter in the item’s state class returns true for even-indexed items, indicating that their state should be preserved. - For odd-indexed items,
wantKeepAlive
returns false, so their state is not preserved when scrolled out of view.
To create a local project with this code sample, run:
flutter create --sample=widgets.SliverChildBuilderDelegate.addAutomaticKeepAlives.1 mysample
By default, ListView.builder only keeps the widgets currently visible in the viewport alive. When an item scrolls out of view, it may be disposed to free up resources. This can cause the state of StatefulWidgets to be lost if not explicitly preserved.
In this example, each item in the list is a StatefulWidget that maintains a counter. Tapping the "+" button increments the counter. To selectively preserve the state, each item is wrapped in a KeepAlive widget, with the keepAlive parameter set based on the item’s index:
- For even-indexed items,
keepAlive: true
, so their state is preserved even when scrolled off-screen. - For odd-indexed items,
keepAlive: false
, so their state is discarded when they are no longer visible.
To create a local project with this code sample, run:
flutter create --sample=widgets.SliverChildBuilderDelegate.addAutomaticKeepAlives.2 mysample
- AutomaticKeepAlive, which allows subtrees to request to be kept alive in lazy lists.
- AutomaticKeepAliveClientMixin, which is a mixin with convenience methods for clients of AutomaticKeepAlive. Used with State subclasses.
- KeepAlive which marks a child as needing to stay alive even when it's in a lazy list that would otherwise remove it.
Implementation
final bool addAutomaticKeepAlives;