Yahav Festinger
Yahav Festinger

Reputation: 1125

Flutter - moving between tabs cause to lose the state

I am issue a weird situation. I have the following code that display the tabs and their contents:

Scaffold(
      appBar: AppBar(
        title: Text('Title'),
        actions: [
          IconButton(
            icon: Icon(Icons.add),
            onPressed: () => _onTabAdd(_tabController.index),
          ),
          IconButton(
            icon: Icon(Icons.delete),
            onPressed: () => _onTabRemoved(_tabController.index),
          ),
          IconButton(
            icon: Icon(Icons.edit),
            onPressed: () => _onTabEdit(context),
          ),
        ],
        bottom: PreferredSize(
          preferredSize: Size.fromHeight(40.0),
          child: Container(
            color: Colors.blue,
            child: TabBar(
              controller: _tabController,
              tabs: tabTitles
                  .map(
                    (title) => Tab(text: title),
                  )
                  .toList(),
              labelColor: Colors.yellow,
              unselectedLabelColor: Colors.white,
              indicatorSize: TabBarIndicatorSize.label,
              indicatorPadding: EdgeInsets.all(5.0),
              indicatorColor: Colors.red,
            ),
          ),
        ),
      ),
      body: TabBarView(
        controller: _tabController,
        children: tabContents.map((e) => e).toList(),
      ),

You can see that I have the option to add or delete Tabs using the buttons, and it seems to work fine using the following functions:

void _onTabRemoved(int index) {
    setState(() {
      tabTitles.removeAt(index);
      tabContents.removeAt(index);
      _tabController = TabController(length: tabTitles.length, vsync: this);
    });
  }

void _onTabAdd(int index) {
    setState(() {
      tabTitles.add("Tab ${tabTitles.length}");
      tabContents.add(GenesTable(this));
      _tabController = TabController(length: tabTitles.length, vsync: this);
    });
  }

The problem is that when I move between tabs I lose the state of GenesTable component (that store the table's content), meaning that when I move between tabs The table that been display is empty.

Upvotes: 3

Views: 1888

Answers (1)

pradyot1996
pradyot1996

Reputation: 1074

You can go through the answer given here https://stackoverflow.com/a/51225319/13927133

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.

And after that override the wantKeepAlive method and return true.

@diegoveloper also posted a medium article for this https://medium.com/@diegoveloper/flutter-persistent-tab-bars-a26220d322bc

Upvotes: 8

Related Questions