I looked online but there are various cases I've tried but failed, it seems so easy yet so difficult is some cases. I have a BottomNavBar in which I made a list of Widgets I want to render, and it works ok (not sure if it's the right approach though). I have a Drawer
and when I press on one of the menu items, I want to render that Widget but with the BottomNavBar being persistent. In other words, almost all screens should render with a persistent BottomNavBar. Here is the code:
Bottom Navigation Bar:
class BottomNavBar extends StatefulWidget {
static const String id = 'bottom_navbar_screen';
@override
_BottomNavBarState createState() => _BottomNavBarState();
}
class _BottomNavBarState extends State<BottomNavBar> {
int _selectedIndex = 0; // the starting screen (can be any of them by changing the starting index)
static List<Widget> _widgetOptions = <Widget>[
Screen1(),
Screen2(),
Screen3(),
Screen4(),
Screen5(),
];
void _onItemTapped(int index) {
setState(() {
_selectedIndex = index;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: _widgetOptions.elementAt(_selectedIndex),
),
bottomNavigationBar: BottomNavigationBar(
items: <BottomNavigationBarItem>[
BottomNavigationBarItem(
label: Tab1,
),
BottomNavigationBarItem(
label: Tab2,
),
BottomNavigationBarItem(
label:Tab3,
),
BottomNavigationBarItem(
label: Tab4,
),
BottomNavigationBarItem(
label: Tab5,
),
],
currentIndex: _selectedIndex,
onTap: _onItemTapped,
),
);
}
}
Now at some point of the app, I have a Drawer
and when I press on one of the menu item inside the Drawer that sends me to let's say Screen2, I just get sent to Screen2 but without the BottomNavBar showing (which is logical but I want to show it, hence the problem I got). I tried with Navigator.push(context, MaterialPageRoute(builder: (context) => Screen2(index: 1),),);
and initializing the index inside the BottomNavBar but failed. Is there a better solution for this type of problem I have?
Thanks in advance for the help!