Reputation: 313
I've created a bottom navigation bar and everytime I use it in different pages its state is back to first item. What am I missing? Thank you.
There are 5 routes defined in a list (and in the main.dart file), so everything is working good except the state.
I've tried with AutomaticKeepAliveClientMixin but I'm not sure that I've used it correctly (it's in the code below).
Here is the code:
class MyBottomNavigationBar extends StatefulWidget {
MyBottomNavigationBar({Key key}) : super(key: key);
@override
MyBottomNavigationBarState createState() => MyBottomNavigationBarState();
}
class MyBottomNavigationBarState extends State<MyBottomNavigationBar>
with AutomaticKeepAliveClientMixin {
int bottomTabIndex = 0;
var routes = ['/', '/', '/my_categories', '/my_people_list', '/my_chat'];
@override
bool get wantKeepAlive => true;
@override
void onTabTapped(int index) {
setState(() {
bottomTabIndex = index;
Navigator.pushNamed(context, routes.elementAt(bottomTabIndex));
});
}
@override
Widget build(BuildContext context) {
theme:
MyFirstTheme().theme;
return BottomNavigationBar(
type: BottomNavigationBarType.fixed,
//
selectedLabelStyle: TextStyle(fontWeight: FontWeight.w700),
unselectedLabelStyle: TextStyle(fontWeight: FontWeight.w700),
iconSize: 24,
items: <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.home),
title: Text(
'HOME',
),
),
BottomNavigationBarItem(
icon: Icon(Icons.insert_chart),
title: Text(
'STATS',
),
),
BottomNavigationBarItem(
icon: Icon(Icons.view_list),
title: Text(
'INVENTORY',
),
),
BottomNavigationBarItem(
icon: Icon(Icons.group),
title: Text(
'PEOPLE',
),
),
BottomNavigationBarItem(
icon: Icon(Icons.forum),
title: Text(
'CHAT',
),
),
],
currentIndex: bottomTabIndex,
onTap: onTabTapped,
);
}
}
Upvotes: 2
Views: 868
Reputation: 54365
You need PageStorage and PageStorageBucket
If you define an widget for bottomNavigationBar, you need to pass page index
code snippet
final List<Widget> pages = [
FirstPage(
key: PageStorageKey('Page1'),
),
SecondPage(
key: PageStorageKey('Page2'),
),
];
...
final PageStorageBucket bucket = PageStorageBucket();
...
@override
Widget build(BuildContext context) {
return Scaffold(
bottomNavigationBar: _bottomNavigationBar(_selectedIndex),
body: PageStorage(
child: pages[_selectedIndex],
bucket: bucket,
),
);
}
You can reference the detail https://medium.com/@lucassaltoncardinali/keeping-state-with-the-bottom-navigation-bar-in-flutter-69e4168878e1
Github code https://github.com/lscardinali/FlutterBottomNavigationBarStatePersistanceSample
demo for github code, you can see page keep its state
Upvotes: 2