Remember the state of bottomNavigation bar when back to a page flutter

304

You can create global.dart file and in it declare int _selectedIndex = 2; and import the file whenever you use it if you set _selectedIndex to a certain value the value is saved with you all over the app.

Share:
304
John Joe
Author by

John Joe

Keep Coding ~

Updated on December 15, 2022

Comments

  • John Joe
    John Joe over 1 year

    In main_activity.dart, there has 4 bottom navigation bar, named A,B,C and D.

    main_activity.dart

    class MainPage extends StatefulWidget {
      static const ROUTE = '/mainPage';
    
      @override
      State<StatefulWidget> createState() => _MainPageState();
    }
    
    class _MainPageState extends State<MainPage> {
      int _selectedIndex = 2;
      final _tabs = [
        A(),
        B(),
        C(),
        D(),
      ];
    
      @override
      Widget build(BuildContext context) {
        return WillPopScope(
          child: Scaffold(
            body: _tabs[_selectedIndex],
            bottomNavigationBar: BottomNavigationBar(
              type: BottomNavigationBarType.fixed,
              currentIndex: _selectedIndex,
              items: [
               ...
              ],
              onTap: (index) => setState(() {
                _selectedIndex = index;
              }),
            ),
          ),
           onWillPop: () => _requestPop(context),
        );
      }
    }
    

    Initially it will open page in tab C. When I click tab B, it will show B page which contains a floating action button. When floating action button is clicked, it will call add_B.dart. My problem is when I click the back button in add_B.dart, it will back to main_activity and open tab C page. How can I make it open tab B page instead?

    add_B.dart

    onWillPop: (){
            _backToPreviousPage(context);
          },
    
     void _backToPreviousPage(BuildContext context) {
        Navigator.of(context).pushReplacementNamed(MainPage.ROUTE);
      }
    
  • John Joe
    John Joe over 4 years
    let say I click the back button in add_B.dart. How can I load tab B state?
  • Mohamed Adel
    Mohamed Adel over 4 years
    before you navigate to the next page set _selectedIndex to the desired index
  • John Joe
    John Joe over 4 years
    yes, I have done that. onTap: (index) => setState(() { _selectedIndex = index; }),
  • John Joe
    John Joe over 4 years
    But when I back from add_B, it load the third tab page @@
  • John Joe
    John Joe over 4 years
    Is it because Navigator.of(context).pushReplacementNamed(MainPage.ROUTE); ?
  • Mohamed Adel
    Mohamed Adel over 4 years
    try to pass _selectedIndex = 1; statically
  • John Joe
    John Joe over 4 years
    how can I pass ? Thanks
  • Mohamed Adel
    Mohamed Adel over 4 years
    onWillPop: () { //here _requestPop(context);}
  • John Joe
    John Joe over 4 years