Flutter › Flutter Widgets Fundamentals (Stateless & Stateful)
How can you properly and correctly implement the AutomaticKeepAliveClientMixin on a specific StatefulWidget to genuinely preserve its own current internal state even when it visually genuinely scrolls entirely off screen within a lazily built list such as one built using ListView.builder?
AdvancedAnswer
Since ListView.builder lazily disposes of any specific individual list item's own widget and its own associated State object once that particular item has genuinely scrolled sufficiently far off screen, a genuinely stateful list item, such as one containing an expanded or collapsed section or an actively playing embedded video, would otherwise incorrectly and unexpectedly lose its own current internal state the moment a user simply scrolls that particular item back out of view and then later scrolls it back again, and properly mixing in AutomaticKeepAliveClientMixin, along with correctly overriding its required wantKeepAlive property to properly return true, explicitly tells Flutter to genuinely keep that specific particular widget's own State object properly and fully alive even while it is not actually currently visible on screen at all.
class _VideoItemState extends State<VideoItem> with AutomaticKeepAliveClientMixin {
@override
bool get wantKeepAlive => true;
@override
Widget build(BuildContext context) {
super.build(context);
return VideoPlayerWidget();
}
}Real-world example A social media feed keeps a specific currently playing embedded video's own actively playing state properly and fully intact even after a user briefly scrolls that particular video item off screen and then genuinely scrolls back to it again shortly afterward, by correctly and properly using AutomaticKeepAliveClientMixin on that specific individual list item widget.