Preserving state between tab view pages

Solution 1:

In case you want to keep the state of your screen in your TabBarView, you can use the mixin class called AutomaticKeepAliveClientMixin in your State class.

After that you have to override the wantKeepAlive method and return true.

I wrote a post about that here: https://medium.com/@diegoveloper/flutter-persistent-tab-bars-a26220d322bc

Solution 2:

Long story short, use a PageStorageKey() for your ListView or one of it's ancestors, the Container widget in your case:

child: Container(
    key: PageStorageKey(page.country),
    child: Newsfeed(country: page.country),
),

See details here:

  • https://api.flutter.dev/flutter/widgets/PageStorageKey-class.html

  • https://api.flutter.dev/flutter/widgets/PageStorage-class.html

  • https://api.flutter.dev/flutter/widgets/ScrollView/controller.html

Solution 3:

Use of the mixin and AutomaticKeepAliveClientMixin on our State.

Implement bool get wantKeepAlive => true; and don't forget to call super.build(context); in your build function

class ResidentListScreen extends StatefulWidget {
  @override
  _ResidentListScreenState createState() => _ResidentListScreenState();
}

class _ResidentListScreenState extends State<ResidentListScreen> with 
AutomaticKeepAliveClientMixin<ResidentListScreen>{

  @override
  bool get wantKeepAlive => true;

  @override
  void initState() {
   super.initState();
  }

  @override
  Widget build(BuildContext context) { 
    super.build(context);
  }
}