Persistent BottomNavigationBar with Routing in Flutter

285

After several attempts, I managed to solve the problem. I needed to save the context of the MainScreen (index.dart -> holds the BottomNavigationBar).

class ContextKeeper {
  static BuildContext buildContext;

  void init(BuildContext context) {
    buildContext = context;
  }
}

lib/screens/main/index.dart:

@override
void initState() {
  super.initState();
  ContextKeeper().init(context); // Save the context
}

Then change

Navigator.of(context).pushAndRemoveUntil(MaterialPageRoute(builder: (context) => LoginScreen(),),(Route<dynamic> route) => false);

to

 Navigator.of(ContextKeeper.buildContext).pushNamedAndRemoveUntil(LoginScreen.id, (route) => false);

and it work's.

Share:
285
Matthias
Author by

Matthias

typing...

Updated on December 13, 2022

Comments

  • Matthias
    Matthias over 1 year

    I have a hard time implementing a persistent BottomNavigationBar in Flutter. My goal is to create a app with several screens and therefore several routes (minimal example):

    app structure for minimal example

    I found this medium article and after struggling a bit with the implementation, I thought that I found the perfect solution. BUT as I wanted to implement a logout function that sends the user back to the LoginScreen the routing doesn't work as expected...

    gif

    As you see in the gif, the problem occours after clicking on the logout button. Instead of navigating back to the LoginScreen, the LoginScreen get's embedded into the MainScreen with the BottomNavigationBar.

    How can I change this behaviour? I thought I would remove all routes with pushAndRemoveUntil...

    // Navigate back to the LoginScreen (this doesn't work as expected...)
              Navigator.of(context).pushAndRemoveUntil(
                  MaterialPageRoute(
                    builder: (context) => LoginScreen(),
                  ),
                  (Route<dynamic> route) => false);
    

    Here is a minimal reproducable example: https://github.com/klasenma/persistent_bottomnavigationbar