127

I'm currently working on building a Flutter app that will preserve states when navigating from one screen, to another, and back again when utilizing BottomNavigationBar. Just like it works in the Spotify mobile application; if you have navigated down to a certain level in the navigation hierarchy on one of the main screens, changing screen via the bottom navigation bar, and later changing back to the old screen, will preserve where the user were in that hierarchy, including preservation of the state.

I have run my head against the wall, trying various different things without success.

I want to know how I can prevent the pages in pageChooser(), when toggled once the user taps the BottomNavigationBar item, from rebuilding themselves, and instead preserve the state they already found themselves in (the pages are all stateful Widgets).

import 'package:flutter/material.dart';
import './page_plan.dart';
import './page_profile.dart';
import './page_startup_namer.dart';

void main() => runApp(new Recipher());

class Recipher extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new Pages();
  }
}

class Pages extends StatefulWidget {
  @override
  createState() => new PagesState();
}

class PagesState extends State<Pages> {
  int pageIndex = 0;


  pageChooser() {
    switch (this.pageIndex) {
      case 0:
        return new ProfilePage();
        break;

      case 1:
        return new PlanPage();
        break;

      case 2:
        return new StartUpNamerPage(); 
        break;  

      default:
        return new Container(
          child: new Center(
            child: new Text(
              'No page found by page chooser.',
              style: new TextStyle(fontSize: 30.0)
              )
            ),
          );     
    }
  }

  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new Scaffold(
        body: pageChooser(),
        bottomNavigationBar: new BottomNavigationBar(
          currentIndex: pageIndex,
          onTap: (int tappedIndex) { //Toggle pageChooser and rebuild state with the index that was tapped in bottom navbar
            setState(
              (){ this.pageIndex = tappedIndex; }
              ); 
            },
          items: <BottomNavigationBarItem>[
            new BottomNavigationBarItem(
              title: new Text('Profile'),
              icon: new Icon(Icons.account_box)
              ),
              new BottomNavigationBarItem(
                title: new Text('Plan'),
                icon: new Icon(Icons.calendar_today)
              ),
                new BottomNavigationBarItem(
                title: new Text('Startup'),
                icon: new Icon(Icons.alarm_on)
              )
            ],
          )
      )
    );
  }
}
ArtBelch
  • 1,279
  • 2
  • 8
  • 4
  • keep each pages using Stack. This might be helpful: https://stackoverflow.com/questions/45235570/how-to-use-bottomnavigationbar-with-navigator/45992604#45992604 – najeira Mar 23 '18 at 02:47
  • Nice, thank you. This worked. I actually already tried to use a IndexedStack, but I now see that this does not work the same way as Offstage and Tickermode. – ArtBelch Mar 24 '18 at 13:19
  • you got your answer yet because I want to do it same way as you mention – Dipak Ramoliya Jan 28 '22 at 05:36

10 Answers10

117

For keeping state in BottomNavigationBar, you can use IndexedStack

    @override
      Widget build(BuildContext context) {
        return Scaffold(
          bottomNavigationBar: BottomNavigationBar(
            onTap: (index) {
              setState(() {
                current_tab = index;
              });
            },
            currentIndex: current_tab,
            items: [
              BottomNavigationBarItem(
                ...
              ),
              BottomNavigationBarItem(
                ...
              ),
            ],
          ),
          body: IndexedStack(
            children: <Widget>[
              PageOne(),
              PageTwo(),
            ],
            index: current_tab,
          ),
        );
      }
Newaj
  • 3,992
  • 4
  • 32
  • 50
  • 45
    But it has performance issue. IndexedStack loads all tab initially which is unnecessary. – Jaya Prakash Aug 11 '20 at 13:38
  • @JayaPrakash So whats your suggestion? – Newaj Aug 11 '20 at 14:57
  • @Newaj initially, i would like to load empty screen after navigating to the specific screen can make network calls. – Jaya Prakash Aug 11 '20 at 16:53
  • 2
    This should be the accepted answer. Works great. @ArtBelch: You'll do us all a favor by marking this answer as the correct one. :) – Teekin Sep 23 '20 at 10:07
  • 2
    @JayaPrakash Did you find a soltion for not building all stacks at once? – anoop4real Oct 05 '20 at 22:13
  • @anoop4real i used to move all building widgets to some other methods and i will update it through from parent widget – Jaya Prakash Oct 06 '20 at 07:51
  • @JayaPrakash what about API calls and stuffs... if you dont mind do you have some write up or gist where I can look? – anoop4real Oct 06 '20 at 12:35
  • 1
    @anoop4real I am using `IndexedStack` to keep preserve the all widget state of tabs and i keep reference for each tab child reference. with on tab change callback i used to call any method inside the child widget with the help of tab child reference. If you need my answer then post a question, i will answer for that. – Jaya Prakash Oct 06 '20 at 15:08
  • for some strange reason if i put the pages on by one in the children attribute at the ```IndexedStack``` , it doesn't work well. It just resets the state on ALL of the pages every time i switch to a new tab. It seems that ```IndexedStack``` needs the pages to be in a ```List``` in order to function as expected. So in the ```children``` attribute i passed the whole list like that ```children: [...myList]``` . I don't know why but that was what i found out.... – Panagiss Dec 06 '20 at 11:05
  • @JayaPrakash Is it a problem though, that the tabs are built immediately? That's straight up how iOS does it. The only problem I can think of is startup time, because the first build is done immediately, rather then when the user accesses the tab. But if it's not any significant, I don't see the reason not to do it. (I'm feeling a premature optimization vibe from it) – Lord Zsolt Jan 27 '21 at 18:11
  • 1
    @JayaPrakash Regarding performance, take a look at this solution: https://stackoverflow.com/questions/66404759/flutter-nested-routing-with-persistent-bottomnavigationbar-but-without-building/66404760#66404760 – filipetrm Feb 28 '21 at 00:36
  • While this works very well, Use `PageView` for parent widget, with `AutomaticKeepAliveClinetMixin` (for individual tabs) if you don't want to load all pages at once. Regardless of any approach, Just make sure you initialize the list of widgets in the `initState` method instead of `build` method – GOBINATH.M Jun 18 '21 at 10:54
95

Late to the party, but I've got a simple solution. Use the PageView widget with the AutomaticKeepAliveClinetMixin.

The beauty of it that it doesn't load any tab until you click on it.


The page that includes the BottomNavigationBar:

var _selectedPageIndex;
List<Widget> _pages;
PageController _pageController;

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

  _selectedPageIndex = 0;
  _pages = [
    //The individual tabs.
  ];

  _pageController = PageController(initialPage: _selectedPageIndex);
}

@override
void dispose() {
  _pageController.dispose();

  super.dispose();
}

@override
Widget build(BuildContext context) {
  ...
    body: PageView(
      controller: _pageController,
      physics: NeverScrollableScrollPhysics(),
      children: _pages,
    ),
   bottomNavigationBar: BottomNavigationBar(
      ...
      currentIndex: _selectedPageIndex,
      onTap: (selectedPageIndex) {
        setState(() {
          _selectedPageIndex = selectedPageIndex;
          _pageController.jumpToPage(selectedPageIndex);
        });
      },
  ...
}

The individual tab:

class _HomeState extends State<Home> with AutomaticKeepAliveClientMixin<Home> {
  @override
  bool get wantKeepAlive => true;

  @override
  Widget build(BuildContext context) {
    //Notice the super-call here.
    super.build(context);
    ...
  }
}

I've made a video about it here.

Tayan
  • 1,707
  • 13
  • 18
46

Use AutomaticKeepAliveClientMixin to force your tab content to not be disposed.

class PersistantTab extends StatefulWidget {
  @override
  _PersistantTabState createState() => _PersistantTabState();
}

class _PersistantTabState extends State<PersistantTab> with AutomaticKeepAliveClientMixin {
  @override
  Widget build(BuildContext context) {
    return Container();
  }

  // Setting to true will force the tab to never be disposed. This could be dangerous.
  @override
  bool get wantKeepAlive => true;
}

To make sure your tab does get disposed when it doesn't require to be persisted, make wantKeepAlive return a class variable. You must call updateKeepAlive() to update the keep alive status.

Example with dynamic keep alive:

// class PersistantTab extends StatefulWidget ...

class _PersistantTabState extends State<PersistantTab>
    with AutomaticKeepAliveClientMixin {
  bool keepAlive = false;

  @override
  void initState() {
    doAsyncStuff();
  }

  Future doAsyncStuff() async {
    keepAlive = true;
    updateKeepAlive();
    // Keeping alive...

    await Future.delayed(Duration(seconds: 10));

    keepAlive = false;
    updateKeepAlive();
    // Can be disposed whenever now.
  }

  @override
  bool get wantKeepAlive => keepAlive;

  @override
  Widget build(BuildContext context) {
    super.build();
    return Container();
  }
}
Charles Crete
  • 944
  • 7
  • 14
15

Instead of returning new instance every time you run pageChooser, have one instance created and return the same.

Example:

class Pages extends StatefulWidget {
  @override
  createState() => new PagesState();
}

class PagesState extends State<Pages> {
  int pageIndex = 0;

  // Create all the pages once and return same instance when required
  final ProfilePage _profilePage = new ProfilePage(); 
  final PlanPage _planPage = new PlanPage();
  final StartUpNamerPage _startUpNamerPage = new StartUpNamerPage();


  Widget pageChooser() {
    switch (this.pageIndex) {
      case 0:
        return _profilePage;
        break;

      case 1:
        return _planPage;
        break;

      case 2:
        return _startUpNamerPage;
        break;

      default:
        return new Container(
          child: new Center(
              child: new Text(
                  'No page found by page chooser.',
                  style: new TextStyle(fontSize: 30.0)
              )
          ),
        );
    }
  }

  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
        home: new Scaffold(
            body: pageChooser(),
            bottomNavigationBar: new BottomNavigationBar(
              currentIndex: pageIndex,
              onTap: (int tappedIndex) { //Toggle pageChooser and rebuild state with the index that was tapped in bottom navbar
                setState(
                        (){ this.pageIndex = tappedIndex; }
                );
              },
              items: <BottomNavigationBarItem>[
                new BottomNavigationBarItem(
                    title: new Text('Profile'),
                    icon: new Icon(Icons.account_box)
                ),
                new BottomNavigationBarItem(
                    title: new Text('Plan'),
                    icon: new Icon(Icons.calendar_today)
                ),
                new BottomNavigationBarItem(
                    title: new Text('Startup'),
                    icon: new Icon(Icons.alarm_on)
                )
              ],
            )
        )
    );
  }
}

Or you can make use of widgets like PageView or Stack to achieve the same.

Hope that helps!

Hemanth Raj
  • 32,555
  • 10
  • 92
  • 82
9

Use “IndexedStack Widget” with “Bottom Navigation Bar Widget” to keep state of Screens/pages/Widget

Provide list of Widget to IndexedStack and index of widget you want to show because IndexedStack show single widget from list at one time.

final List<Widget> _children = [
    FirstClass(),
    SecondClass()
  ];

Scaffold(
  body: IndexedStack(
    index: _selectedPage,
    children: _children,
  ),
  bottomNavigationBar: BottomNavigationBar(
    ........
    ........
  ), 
);
Techalgoware
  • 540
  • 6
  • 11
5

The most convenient way I have found to do so is using PageStorage widget along with PageStorageBucket, which acts as a key value persistent layer.

Go through this article for a beautiful explanation -> https://steemit.com/utopian-io/@tensor/persisting-user-interface-state-and-building-bottom-navigation-bars-in-dart-s-flutter-framework

Anirudh Agarwal
  • 2,044
  • 2
  • 14
  • 8
2

Do not use IndexStack Widget, because it will instantiate all the tabs together, and suppose if all the tabs are making a network request then the callbacks will be messed up the last API calling tab will probably have the control of the callback.

Use AutomaticKeepAliveClientMixin for your stateful widget it is the simplest way to achieve it without instantiating all the tabs together.

My code had interfaces that were providing the respective responses to the calling tab I implemented it the following way.

Create your stateful widget

class FollowUpsScreen extends StatefulWidget {
  FollowUpsScreen();
        
  @override
  State<StatefulWidget> createState() {
    return FollowUpsScreenState();
  }
}
        
class FollowUpsScreenState extends State<FollowUpsScreen>
     with AutomaticKeepAliveClientMixin<FollowUpsScreen>
            implements OperationalControls {
    
  @override
  Widget build(BuildContext context) {
  //do not miss this line
    super.build(context);
    return .....;
  }

  @override
  bool get wantKeepAlive => true;
}
MahMoos
  • 1,014
  • 9
  • 16
Swapnil Kadam
  • 4,075
  • 5
  • 29
  • 35
1

This solution is based on CupertinoTabScaffold's implementation which won't load screens unnecessary.

import 'package:flutter/material.dart';

enum MainPage { home, profile }

class BottomNavScreen extends StatefulWidget {
  const BottomNavScreen({super.key});

  @override
  State<BottomNavScreen> createState() => _BottomNavScreenState();
}

class _BottomNavScreenState extends State<BottomNavScreen> {
  var currentPage = MainPage.home;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: PageSwitchingView(
        currentPageIndex: MainPage.values.indexOf(currentPage),
        pageCount: MainPage.values.length,
        pageBuilder: _pageBuilder,
      ),
      bottomNavigationBar: BottomNavigationBar(
        currentIndex: MainPage.values.indexOf(currentPage),
        onTap: (index) => setState(() => currentPage = MainPage.values[index]),
        items: const [
          BottomNavigationBarItem(
            label: 'Home',
            icon: Icon(Icons.home),
          ),
          BottomNavigationBarItem(
            label: 'Profile',
            icon: Icon(Icons.account_circle),
          ),
        ],
      ),
    );
  }

  Widget _pageBuilder(BuildContext context, int index) {
    final page = MainPage.values[index];

    switch (page) {
      case MainPage.home:
        return ...
      case MainPage.profile:
        return ...
    }
  }
}

/// A widget laying out multiple pages with only one active page being built
/// at a time and on stage. Off stage pages' animations are stopped.
class PageSwitchingView extends StatefulWidget {
  const PageSwitchingView({
    super.key,
    required this.currentPageIndex,
    required this.pageCount,
    required this.pageBuilder,
  });

  final int currentPageIndex;
  final int pageCount;
  final IndexedWidgetBuilder pageBuilder;

  @override
  State<PageSwitchingView> createState() => _PageSwitchingViewState();
}

class _PageSwitchingViewState extends State<PageSwitchingView> {
  final List<bool> shouldBuildPage = <bool>[];

  @override
  void initState() {
    super.initState();
    shouldBuildPage.addAll(List<bool>.filled(widget.pageCount, false));
  }

  @override
  void didUpdateWidget(PageSwitchingView oldWidget) {
    super.didUpdateWidget(oldWidget);

    // Only partially invalidate the pages cache to avoid breaking the current
    // behavior. We assume that the only possible change is either:
    // - new pages are appended to the page list, or
    // - some trailing pages are removed.
    // If the above assumption is not true, some pages may lose their state.
    final lengthDiff = widget.pageCount - shouldBuildPage.length;
    if (lengthDiff > 0) {
      shouldBuildPage.addAll(List<bool>.filled(lengthDiff, false));
    } else if (lengthDiff < 0) {
      shouldBuildPage.removeRange(widget.pageCount, shouldBuildPage.length);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      fit: StackFit.expand,
      children: List<Widget>.generate(widget.pageCount, (int index) {
        final active = index == widget.currentPageIndex;
        shouldBuildPage[index] = active || shouldBuildPage[index];

        return HeroMode(
          enabled: active,
          child: Offstage(
            offstage: !active,
            child: TickerMode(
              enabled: active,
              child: Builder(
                builder: (BuildContext context) {
                  return shouldBuildPage[index] ? widget.pageBuilder(context, index) : Container();
                },
              ),
            ),
          ),
        );
      }),
    );
  }
}
maRci002
  • 341
  • 3
  • 7
  • Yes, it inded keeps state. I have an opposite question: I am using CupertinoTabScaffold but I dont want to keep state. Is there any workaround? – Behzod Faiziev Feb 18 '23 at 18:19
  • 1
    Provide your own `CupertinoTabController` and listen to changes so when index changes provide an incremented Key to your `tabBuilder'`s child. – maRci002 Feb 19 '23 at 19:36
0

proper way of preserving tabs state in bottom nav bar is by wrapping the whole tree with PageStorage() widget which takes a PageStorageBucket bucket as a required named parameter and for those tabs to which you want to preserve its state pas those respected widgets with PageStorageKey(<str_key>) then you are done !! you can see more details in this ans which i've answered few weeks back on one question : https://stackoverflow.com/a/68620032/11974847

there's other alternatives like IndexedWidget() but you should beware while using it , i've explained y we should be catious while using IndexedWidget() in the given link answer

good luck mate ..

Himmat rai
  • 57
  • 1
  • 6
0

Summary of Solutions: Two Approaches Offered

Solution 1: AutomaticKeepAliveClientMixin

class SubPage extends StatefulWidget {
  @override
  State<SubPage> createState() => _SubPageState();
}

class _SubPageState extends State<SubPage> with AutomaticKeepAliveClientMixin {
  @override
  Widget build(BuildContext context) {
    super.build(context); // Ensure that the mixin is initialized
    return Container();
  }

  @override
  bool get wantKeepAlive => true;
}
/*-------------------------------*/
class MainPage extends StatefulWidget {
  const MainPage({Key? key}) : super(key: key);

  @override
  State<MainPage> createState() => _MainPageState();
}

class _MainPageState extends State<MainPage> {
  int currentBottom = 0;

  static const List<Widget> _page = [
    SubPage(),
    SubPage(),
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        bottomNavigationBar: BottomNavigationBar(
          currentIndex: currentBottom,
          onTap: (index) => setState(() {
            currentBottom = index;
          }),
          items: const [
            BottomNavigationBarItem(icon: Icon(Icons.home)),
            BottomNavigationBarItem(icon: Icon(Icons.settings))
          ],
        ),
        body: _page.elementAt(currentBottom));
  }
}

Solution 2: IndexedStack

class MainPage extends StatefulWidget {
  @override
  _MainPageState createState() => _MainPageState();
}

class _MainPageState extends State<MainPage> {
  int _currentIndex = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: IndexedStack(
        index: _currentIndex,
        children: <Widget>[
          Page1(),
          Page2(),
          Page3(),
        ],
      ),
      bottomNavigationBar: BottomNavigationBar(
        currentIndex: _currentIndex,
        onTap: (int index) {
          setState(() {
            _currentIndex = index;
          });
        },
        items: [
          BottomNavigationBarItem(
            icon: Icon(Icons.home),
            label: 'Page 1',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.search),
            label: 'Page 2',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.settings),
            label: 'Page 3',
          ),
        ],
      ),
    );
  }
}
/*--------------------------------*/
class Page1 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      // Page 1 content
    );
  }
}
// Repeat the above for Page2 and Page3
DuocNP
  • 34
  • 4