Persistent BottomNavigationBar with Routing in Flutter
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.
Comments
-
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):
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...
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