Flutter Bottom Navigation Bar with PageView
6,899
Solution 1
You just need to use onPageChanged
property of the PageView to catch the current page number.
PageView(
controller: _pageController,
children: <Widget>[
ProfilePage(),
HomeTables(),
ShoppingPage(),
],
onPageChanged: (page) {
setState(() {
_selectedIndex = page;
});
},
);
Solution 2
Just add onPageChanged property of PageView
and assign the pageIndex
to _selectedIndex
property, then reload the widget using setState()
method.
onPageChanged - Called whenever the page in the center of the viewport changes.
PageView(
....
onPageChanged: (pageIndex) {
setState(() {
_selectedIndex = pageIndex;
});
},
...
)
Author by
Admin
Updated on December 16, 2022Comments
-
Admin over 1 year
I want to build bottom navigation bar with a pageview. It will be 3 pages and you can transition left or right. I can slide but my navigation bar selected items color doesn't change. Can you help me?
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); } }