Is there a way to show the BottomNavigationBar on every page? Currently the BottomNavigationBar disappears when pushing the button but I want the BottomNavigationBar to always be displayed even when routing to a new page. The following code shows my BottomNavigationBar and my detail page.
class BottomNavBar extends StatefulWidget {
const BottomNavBar({Key? key}) : super(key: key);
@override
State<BottomNavBar> createState() => _BottomNavBarState();
}
class _BottomNavBarState extends State<BottomNavBar> {
int currentIndex = 0;
final screens = const [Home(), Search()];
@override
Widget build(BuildContext context) {
return Scaffold(
body: screens[currentIndex],
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.fixed,
backgroundColor: bottomNav,
unselectedItemColor: Colors.grey,
selectedFontSize: 12,
unselectedFontSize: 12,
currentIndex: currentIndex,
onTap: (index) => setState(() => currentIndex = index),
items: const [
BottomNavigationBarItem(
icon: Icon(
Icons.home_filled,
size: 28,
),
label: 'Home'),
BottomNavigationBarItem(
icon: Icon(
Icons.search_rounded,
size: 28,
),
label: 'Search'),
]));
}
}
My detail page:
class Home extends StatelessWidget {
const Home({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: IconButton(
icon: const Icon(Icons.abc),
onPressed: () {
Navigator.push(
context, MaterialPageRoute(builder: (context) => const Page1()));
},
)),
);
}
}
class Page1 extends StatelessWidget {
const Page1({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Container(
color: Colors.red,
);
}
}
CodePudding user response:
Well, it should show on every page If all those pages (where you want to show this bar) have been put under the same Scaffold. Here's what I usually do:
Create a list that holds the pages you want to show bottomNavigationBar on :
List subScreens = [SubScreen1(), SubScreen2(), SubScreen3()]
Now, create a base page/screen which would render these subscreens like this:
return Scaffold(
bottomNavigationBar: BottomNavigationBar(),
body: subScreens[stateCounter],
);
Now use this stateCounter as currentIndex to your BottomNavigationBar() as well as to also fetch the correct subscreen from the list.
CodePudding user response:
If you want to show this navigation bar on all pages, do not use the Scaffold you used in BottomNavBar on your other pages. Because with each new Scaffold you set the BottomNavigationBar parameter of other pages to empty.