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

Viewed 345

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);
  }
1 Answers

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.

Related