Search code examples
fluttermobilebottomnavigationview

Flutter Bottom Navigation Bar with PageView


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);
}
}

Solution

  • 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;
              });
            },
        );