I have been writing a simple app which uses bottom navigation bar.
Basic usage of navigate between pages with Navigator is done as such:
Navigator.of(context).push(...);
When I first use bottom navigation bar, I automatically assume that Bottom navigation bar persists in almost all pages unless it is told to disappear, which I believe to be an desired or expected behavior.
So, rather than asking about how to persist, or control bottom navigation bar across an app, I want to ask following questions:
Am I approaching(thinking) the bottom navigation bar in a wrong way? Is my expectation towards bottom navigation bar wrong?
If not, then what are the reasons bottom navigation bar should disappear when using navigation methods such as push and pop?
Lastly, what do I need to know in order to understand flutter's navigation and bottom navigation bar?
thank you!
CodePudding user response:
Yes, your assumptions are wrong. Pushing or popping pages will make the bar disappear (unless those pages also have a bar)
I think your key misunderstanding is that you think you need to use
Navigator
and push and pop pages when you use the bar. You are not supposed to useNavigator
when just switching tabs using the bar. Every single tab is still the same page, you just switch the content of your page by using the buttons in the bottom bar.
The best way to understanding is probably to just examine and play with the examples on the offical documentation of BottomNavigationBar
here . You can try it out and run it right on that page
CodePudding user response:
To change pages, while persisting the bottom app bar, use the pag eview widget. It acceptes children screens to which you can navigate to, without creating a new stack. Here's an example-
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
int _selectedIndex = 0;
final PageController _pageController = PageController();
@override
Widget build(BuildContext context) {
return Scaffold(
bottomNavigationBar: BottomNavigationBar(
items: [
BottomNavigationBarItem(
icon: Icon(Icons.portrait), title: Text('Profile')),
BottomNavigationBarItem(icon: Icon(Icons.home), title: Text('Home')),
BottomNavigationBarItem(
icon: Icon(Icons.shopping_cart), title: Text('Shop'))
],
onTap: _onTappedBar,
selectedItemColor: Colors.orange,
currentIndex: _selectedIndex,
),
body: PageView(
controller: _pageController,
children: <Widget>[
ProfilePage(),
HomeTables(),
ShoppingPage(),
],
),
);
}
void _onTappedBar(int value) {
setState(() {
_selectedIndex = value;
});
_pageController.jumpToPage(value);
}
}