Flutter 如何通过单击Flatter中页面中的按钮导航到BottomNavigationBar的其中一个页面?
我有一个底部导航栏在我的颤振应用程序,它是用来显示不同的页面。我需要单击其中一个页面中的按钮来导航到另一个页面,该页面也可以通过底部的导航栏进行导航。为了保持页面的状态,我使用了IndexedStack小部件。同时,我会突出显示我当前所在的页面。 如何做到这一点。 这是代码Flutter 如何通过单击Flatter中页面中的按钮导航到BottomNavigationBar的其中一个页面?,flutter,Flutter,我有一个底部导航栏在我的颤振应用程序,它是用来显示不同的页面。我需要单击其中一个页面中的按钮来导航到另一个页面,该页面也可以通过底部的导航栏进行导航。为了保持页面的状态,我使用了IndexedStack小部件。同时,我会突出显示我当前所在的页面。 如何做到这一点。 这是代码 class IndexPage extends StatefulWidget { @override _IndexPageState createState() => _IndexPageState(); }
class IndexPage extends StatefulWidget {
@override
_IndexPageState createState() => _IndexPageState();
}
class _IndexPageState extends State<IndexPage>
with SingleTickerProviderStateMixin {
final ValueNotifier<int> pageNumberNotifier = ValueNotifier<int>(0);
final List<Widget> _widgets = <Widget>[
Page1(),
Page2(),
Page3(),
];
@override
void dispose() {
super.dispose();
pageNumberNotifier.dispose();
}
@override
Widget build(BuildContext context) {
return ValueListenableBuilder(
valueListenable: pageNumberNotifier,
builder: (BuildContext context, int pageNumber, Widget child) {
return SafeArea(
child: Scaffold(
body: IndexedStack(
index: pageNumberNotifier.value,
children: _widgets,
),
bottomNavigationBar: BottomNavigationBar(
showUnselectedLabels: true,
currentIndex: pageNumber,
onTap: (index) => pageNumberNotifier.value = index,
items: <BottomNavigationBarItem>[
bottomNavigationBarItem(
iconString: 'page1', index: 0, title: 'Page1'),
bottomNavigationBarItem(
iconString: 'page2', index: 1, title: 'Page2'),
bottomNavigationBarItem(
iconString: 'page3', index: 2, title: 'Page3'),
],
),
),
);
});
}
BottomNavigationBarItem bottomNavigationBarItem(
{String iconString, int index, String title}) {
//shows the icons and also highlights the icon of the current page based on the current index.
}
}
使用GlobalKey
GlobalKey<_IndexPageState> key = GlobalKey();
使用以下命令从任意位置调用此方法:
key.currentState.setPage(0);
void setPage(int page) {
pageNumberNotifier.value = page;
}
key.currentState.setPage(0);