I've been looking through multiple tutorials about the bottom navigation bar. Every single tutorial puts the bottom navigation bar in the main flutter file, which I don't like. I'm trying to modularize the app and put the bottom navigation bar in a second file with getters and setters to change and monitor the current view in place, but it's not working for me. I've tried to create setters and getters in the app file to be accessed by the navigation bar to handle navigation like this:
class _AppState extends State<App> {
int _selectedPage = 0;
final _pages = [HomePage(), EventsPage(), ThrivePage(), AnnouncementsPage()];
int get currentPage => this._selectedPage;
set currentPage(int thePage) {
this._selectedPage = thePage;
}
and the bottom navigation widget file would access it, but there's no actual variable for the App class so I can't access the class getters and setters.
I'm pretty new to OOP so there may be an approach I'm not familiar with. Any help is appreciated.
This might not be what you want to hear now but you could create a custom tab and use a pageview as your views then use the pageview controller to change between screens now the custom navigation can be any file you just have to link them correctly. I think I might write an article to really explain what I have said
You can use ValueNotifier
to pass value between different widget. Make your bottom navigation class to take a ValueNotifier in constructor and add a listener to it.
class MyBottomNavigationBar extends StatefulWidget {
final ValueNotifier<int> currentPageNotifier;
MyBottomNavigationBar(this.currentPageNotifier);
@override
_MyBottomNavigationBarState createState() => _MyBottomNavigationBarState();
}
class _MyBottomNavigationBarState extends State<MyBottomNavigationBar> {
@override
void initState() {
super.initState();
widget.currentPageNotifier.addListener(() {
print(widget.currentPageNotifier.value);
});
}
@override
Widget build(BuildContext context) {
return Container();
}
}
From _AppState
pass a ValueNotifier to MyBottomNavigationBar
instance, then you can use that ValueNotifier to pass page index value to MyBottomNavigationBar
class _AppState extends State<App> {
ValueNotifier<int> _currentPageNotifier = ValueNotifier(0);
int _selectedPage = 0;
int get currentPage => this._selectedPage;
set currentPage(int thePage) {
this._selectedPage = thePage;
this._currentPageNotifier.value = thePage;
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Text(
'You have pushed the button this many times:',
),
),
bottomNavigationBar: MyBottomNavigationBar(_currentPageNotifier),// This trailing comma makes auto-formatting nicer for build methods.
);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.