Remember the state of bottomNavigation bar when back to a page flutter
304
You can create global.dart
file and in it declare int _selectedIndex = 2;
and import the file whenever you use it if you set _selectedIndex
to a certain value the value is saved with you all over the app.
Comments
-
John Joe over 1 year
In
main_activity.dart
, there has 4 bottom navigation bar, named A,B,C and D.main_activity.dart
class MainPage extends StatefulWidget { static const ROUTE = '/mainPage'; @override State<StatefulWidget> createState() => _MainPageState(); } class _MainPageState extends State<MainPage> { int _selectedIndex = 2; final _tabs = [ A(), B(), C(), D(), ]; @override Widget build(BuildContext context) { return WillPopScope( child: Scaffold( body: _tabs[_selectedIndex], bottomNavigationBar: BottomNavigationBar( type: BottomNavigationBarType.fixed, currentIndex: _selectedIndex, items: [ ... ], onTap: (index) => setState(() { _selectedIndex = index; }), ), ), onWillPop: () => _requestPop(context), ); } }
Initially it will open page in tab C. When I click tab B, it will show B page which contains a floating action button. When floating action button is clicked, it will call
add_B.dart
. My problem is when I click the back button inadd_B.dart
, it will back tomain_activity
and open tab C page. How can I make it open tab B page instead?add_B.dart
onWillPop: (){ _backToPreviousPage(context); }, void _backToPreviousPage(BuildContext context) { Navigator.of(context).pushReplacementNamed(MainPage.ROUTE); }
-
John Joe over 4 yearslet say I click the back button in
add_B.dart
. How can I load tab B state? -
Mohamed Adel over 4 yearsbefore you navigate to the next page set _selectedIndex to the desired index
-
John Joe over 4 yearsyes, I have done that.
onTap: (index) => setState(() { _selectedIndex = index; }),
-
John Joe over 4 yearsBut when I back from add_B, it load the third tab page @@
-
John Joe over 4 yearsIs it because
Navigator.of(context).pushReplacementNamed(MainPage.ROUTE);
? -
Mohamed Adel over 4 yearstry to pass _selectedIndex = 1; statically
-
John Joe over 4 yearshow can I pass ? Thanks
-
Mohamed Adel over 4 yearsonWillPop: () { //here _requestPop(context);}
-
John Joe over 4 yearsLet us continue this discussion in chat.