我正在尝试在Flutter中创建BottomNavigationBar,但是我想禁用页面之间的幻灯片动画。如果我从第一个标签转到第三个标签,我希望它直接打开第三个标签,而不是先滑过secondtab再滑到Thirdtab。
这是我的代码:
class MyApp3 extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return _MyAppState3();
}
}
class _MyAppState3 extends State<MyApp3> {
@override
PageController _pageController;
@override
void initState() {
super.initState();
_pageController = PageController(initialPage: 0);
}
@override
Widget build(BuildContext context) {
var pages = [FirstTab(), SecondTab(), ThirdTab()];
var pageView = PageView(
controller: _pageController,
physics: NeverScrollableScrollPhysics(),
children: pages,
);
var bottomNav = BottomNavigationBar(
onTap: (tabIndex) {
_pageController.jumpToPage(tabIndex);
},
items: [
BottomNavigationBarItem(icon: Icon(Icons.home), label: "Start"),
BottomNavigationBarItem(
icon: Icon(Icons.camera_enhance), label: "Second"),
BottomNavigationBarItem(icon: Icon(Icons.offline_pin), label: "Home"),
],
);
return MaterialApp(
home: Scaffold(
body: pageView,
bottomNavigationBar: bottomNav,
));
}
}
使用此代码,一切都可以按我的要求进行,但是页面更改时BottomNavigationBarItem不会更改。总是这样:
如何更改BottomNavigationBarItem选择?
答案 0 :(得分:1)
尝试一下。
class MyApp3 extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return _MyAppState3();
}
}
class _MyAppState3 extends State<MyApp3> {
@override
PageController _pageController;
@override
void initState() {
super.initState();
_pageController = PageController(initialPage: 0);
}
int _currentIndex = 0;
@override
Widget build(BuildContext context) {
var pages = [FirstTab(), SecondTab(), ThirdTab()];
var pageView = PageView(
controller: _pageController,
physics: NeverScrollableScrollPhysics(),
children: pages,
);
var bottomNav = BottomNavigationBar(
onTap: (tabIndex) {
setState((){_currentIndex = tabIndex;});
_pageController.jumpToPage(tabIndex);
},
currentIndex: _currentIndex,
items: [
BottomNavigationBarItem(icon: Icon(Icons.home), label: "Start"),
BottomNavigationBarItem(
icon: Icon(Icons.camera_enhance), label: "Second"),
BottomNavigationBarItem(icon: Icon(Icons.offline_pin), label: "Home"),
],
);
return MaterialApp(
home: Scaffold(
body: pageView,
bottomNavigationBar: bottomNav,
));
}
}