12

I have a TabBarView in my main.dart and every tab got a class to show the content(it's listview object), when i go between the tabs, the listview page refresh everytime, is it normal for tabbarview? I don't expect it will refresh everytime when i go between the tabs.

is it the problem my class? how to fix this? the code is something like this.

    class ListWidget extends StatefulWidget {
  final catID;

  ListWidget(this.catID);


  _ListWidgetState createState() => new _ListWidgetState(catID);
}

class _ListWidgetState extends State<ListWidget> {

  var catID;

  void initState() {
    super.initState();
    _fetchListData();
  }

  @override

  Widget build(BuildContext context) {
    // TODO: implement build

    return new Scaffold(.......
}
Armali
  • 18,255
  • 14
  • 57
  • 171
Niccolo
  • 933
  • 4
  • 12
  • 17

3 Answers3

29

MahMoos is right, however it's good to have an example here ...

  1. Use AutomaticKeepAliveClientMixin
  2. override wantKeepAlive property and return true

`

class ListWidget extends StatefulWidget {

  @override
  _ListWidgetState createState() => _ListWidgetState();

}

class _ListWidgetState extends State<ListWidget> with 
                  AutomaticKeepAliveClientMixin<ListWidget>{ // ** here

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

  @override
  bool get wantKeepAlive => true; // ** and here
}
Robert Apikyan
  • 1,972
  • 1
  • 20
  • 23
10

If I understood you well, you are complaining about the refreshing because you need the views to save their states after moving between tabs. There is an open issue on the subject and there is a way around this problem mentioned in the comments.

Update:

There is a workaround for this issue by using AutomaticKeepAliveClientMixin which you can learn more about in this article.

MahMoos
  • 1,014
  • 9
  • 16
4

If you want that your Tab view data does not refresh when you change Tab you should use

AutomaticKeepAliveClientMixin

class BaseScreen extends StatefulWidget {

  BaseScreen(this.title, this.listener, {Key key}) : super(key: key);

}

class BaseScreenState extends State<BaseScreen> with AutomaticKeepAliveClientMixin {

  @override
  Widget build(BuildContext context) {
    screenWidth = MediaQuery.of(context).size.width;
    screenHeight = MediaQuery.of(context).size.height;
    primaryColor = Theme.of(context).primaryColor;
    textTheme = Theme.of(context).textTheme;
    return Scaffold(
      key: scaffoldKey,
      appBar: getAppBar(),
      body: Container(),
    );
  }

  @override
  bool get wantKeepAlive => true;
}

I was facing the same issue and this tutorial helped me.

Happy Coding.

Anuj Sharma
  • 4,294
  • 2
  • 37
  • 53