我想用浏览量构建底部导航栏。这将是3页,您可以向左或向右过渡。我可以滑动,但导航栏上所选项目的颜色不会改变。你能帮我吗?
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);
}
}
答案 0 :(得分:4)
您只需要使用PageView的onPageChanged
属性即可捕获当前页码。
PageView(
controller: _pageController,
children: <Widget>[
ProfilePage(),
HomeTables(),
ShoppingPage(),
],
onPageChanged: (page) {
setState(() {
_selectedIndex = page;
});
},
);
答案 1 :(得分:2)
只需添加PageView
的{{3}}属性并将pageIndex
分配给_selectedIndex
属性,然后使用setState()
方法重新加载小部件。
onPageChanged -每当视口中心的页面更改时调用。
PageView(
....
onPageChanged: (pageIndex) {
setState(() {
_selectedIndex = pageIndex;
});
},
...
)