15

I have a TabBarView with 3 TabBar. When I'm in tab 1 I do something, then I navigate to tab 2 when I come back to tab 1 I want to the previous state of tab 1 will not change.

How can I achieve this in Flutter?

Below is my code screenshot

class _LandingPageState extends State<LandingPage> with SingleTickerProviderStateMixin {
  int _selectedIndex = 0;
  PageController pageController;
  TabController tabController;

  @override
  void initState() {
    tabController = TabController(length: 3, vsync: this, initialIndex: 0);
    pageController = PageController(initialPage: 0)
      ..addListener(() {
        setState(() {
          _selectedIndex = pageController.page.floor();
        });
      });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
              bottomNavigationBar: BottomNavigationBar(
              currentIndex: _selectedIndex,
              onTap: (index) {
                setState(() {
                  _selectedIndex = index;
                  tabController.animateTo(index,
                      duration: Duration(microseconds: 300),
                      curve: Curves.bounceIn);
                });
              },
              items: [
                BottomNavigationBarItem(
                    icon: Icon(Icons.assignment), title: Text("Các yêu cầu")),
                BottomNavigationBarItem(
                    icon: Icon(Icons.history), title: Text("Lịch sử")),
                BottomNavigationBarItem(
                    icon: Icon(Icons.person), title: Text("Hồ sơ")),
              ]),
          body: TabBarView(
              controller: tabController,
              children: [
                RequestPage(key: PageStorageKey<String>("request_page"),),
                HistoryPage(key: PageStorageKey<String>("history_page")),
                ProfilePage(key: PageStorageKey<String>("profile_page"))])
          ),
    );
  }

enter image description here

Miguel Ruivo
  • 16,035
  • 7
  • 57
  • 87

3 Answers3

41

Make sure that all of your TabBarView children are StatefulWidgets and then add a AutomaticKeepAliveClientMixin like so in all of them, for example, for your RequestPage, it should look like this:

class RequestPage extends StatefulWidget {
  RequestPage({Key key}) : super(key: key);

  @override
  _RequestPageState createState() => _RequestPageState();
}

class _RequestPageState extends State<RequestPage> with AutomaticKeepAliveClientMixin{
  @override
  Widget build(BuildContext context) {
    super.build(context);
    return // Your widget tree
  }

  @override
  bool get wantKeepAlive => true;
}
Miguel Ruivo
  • 16,035
  • 7
  • 57
  • 87
  • 1
    Is any drawback with this approach? – Hoang Trung Nguyen Apr 23 '20 at 10:51
  • 6
    No, it's actually one of the most correct ways to do so, that's exactly for that the `AutomaticKeepAliveClientMixin` exists. However, have in mind that `AutomaticKeepAliveClientMixin` will only work under keepAlive notifiers, such as `TabBarView`, `ListView` and a few more. Those are the parent widgets that iterate over its children and "ask" whether they should keep alive or recycled. If you use `AutomaticKeepAliveClientMixin` without any of those parents, it won't have any effect. – Miguel Ruivo Apr 23 '20 at 11:14
  • 4
    Best answer! Followed instructions and worked like a charm! Make all TabBarView children **Stateful**, conform all children to **AutomaticKeepAliveClientMixin** , override **wantKeepAlive** in all children, and called **super.build(context)** inside the build method of all the children. – Masterfego Jan 16 '22 at 19:10
1

Try AutomaticKeepAliveClientMixin and override wantKeepAlive to always return true

0

As the body of Scaffold Use IndexedStack to preserve state. Example :

      @override
      Widget build(BuildContext context) {
        return Scaffold(
          bottomNavigationBar: BottomNavigationBar(
            onTap: (index) {
              setState(() {
                _selectedIndex = index;
              });
            },
            currentIndex: _selectedIndex,
            items: [
              BottomNavigationBarItem(
                ...
              ),
              BottomNavigationBarItem(
                ...
              ),
            ],
          ),
          body: IndexedStack(
            children: <Widget>[
              PageOne(),
              PageTwo(),
            ],
            index: _selectedIndex,
          ),
        );
      }
Newaj
  • 3,992
  • 4
  • 32
  • 50