addAutomaticKeepAlives property

bool addAutomaticKeepAlives
final

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.

This sample demonstrates how to use the AutomaticKeepAlive widget in combination with the AutomaticKeepAliveClientMixin to selectively preserve the state of individual items in a scrollable list.

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.
link

To create a local project with this code sample, run:
flutter create --sample=widgets.SliverChildBuilderDelegate.addAutomaticKeepAlives.1 mysample

This sample demonstrates how to use the KeepAlive widget to preserve the state of individual list items in a ListView when they are scrolled out of view.

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.
link

To create a local project with this code sample, run:
flutter create --sample=widgets.SliverChildBuilderDelegate.addAutomaticKeepAlives.2 mysample

Implementation

final bool addAutomaticKeepAlives;