11

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

2 Answers2

12

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;
          });
        },
    );
jarekbutek
  • 585
  • 6
  • 13
3

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;
    });
  },
  ...
)
Vinoth Vino
  • 9,166
  • 3
  • 66
  • 70