Reputation: 353
I have a bottom bar that is supposed to switch between screens when selected but I do not know how to make that work. I know is all contained in the buildpages() widget. Can you guide me through?
Widget buildBottomBar() {
final style = TextStyle(color: Colors.white);
return BottomNavigationBar(
backgroundColor: Colors.deepOrange,
selectedItemColor: Colors.white,
unselectedItemColor: Colors.black,
showSelectedLabels: true,
showUnselectedLabels: false,
selectedLabelStyle: TextStyle(color: Colors.black54),
currentIndex: index,
items: [
BottomNavigationBarItem(
icon: Text('App', style: style),
label: 'Idioms List',
activeIcon: Icon(Icons.list)
),
BottomNavigationBarItem(
icon: Text('FAVORITES', style: style),
label: 'Favorited',
activeIcon: Icon(Icons.favorite_border_rounded)
),
],
onTap: (int index) => setState(() => this.index = index),
);
}
Widget buildPages() {
switch (index) {
case 0:
return FavoriteScreen();
case 1:
return MainPage();
default:
return Container();
}
}
}
Upvotes: 2
Views: 354
Reputation: 68
you need to create a page for bottom nav bar and give stful widget then create a list of page like this
static const List<Widget> _widgetOptions = <Widget>[
YorPageclass1(),
YourPageclass2(), etc...];
and create a function for Ontap like
void _onItemTapped(int index) {
setState(() {
_selectedIndex = index;
});}
and create a scaffold widget for pages
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('BottomNavigationBar Sample'),
),
body: Center(
child: _widgetOptions.elementAt(_selectedIndex),
),
bottomNavigationBar: BottomNavigationBar(
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.home),
label: 'Home',
),
BottomNavigationBarItem(
icon: Icon(Icons.business),
label: 'Business',
),
BottomNavigationBarItem(
icon: Icon(Icons.school),
label: 'School',
),
],
currentIndex: _selectedIndex,
selectedItemColor: Colors.amber[800],
onTap: _onItemTapped,
),
);
}
Upvotes: 1