gpt4 book ai didi

flutter - 我应该如何在导航到另一个屏幕时更改 BottomNavigationBar 的 currentIndex 属性?

转载 作者:行者123 更新时间:2023-12-05 05:46:59 24 4
gpt4 key购买 nike

我的 Flutter 应用程序有一个底部导航栏小部件。在点击特定项目时,它会导航到另一个屏幕。但是,我不知道在这种情况下如何更新当前索引,以便突出显示选定的选项卡。这是我的代码:

        BottomNavigationBar(
backgroundColor: const Color(0xffFF7B19),
items: <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(
Icons.calendar_today_rounded,
size: lh / 25,
),
label: 'Events',
),
BottomNavigationBarItem(
icon: Icon(
Icons.people_alt_outlined,
size: lh / 25,
),
label: 'Councils',
),
],
currentIndex: 0,
selectedItemColor: Colors.grey[900],
unselectedItemColor: Colors.grey[50],
onTap: (int index) {
if (index == 0) {
Navigator.push(context,
MaterialPageRoute(builder: (context) => AllEventsScreen()));
} else {
Navigator.push(
context, MaterialPageRoute(builder: (context) => Councils()));
}
})

Here is the output

我已经尝试为此创建一个变量 _selectedIndex,我正在为 onTap 提供的函数中更新它,如下所示:

          currentIndex: _selectedIndex,
selectedItemColor: Colors.grey[900],
unselectedItemColor: Colors.grey[50],
onTap: (int index) {
if (index == 0) {
Navigator.push(context,
MaterialPageRoute(builder: (context) => AllEventsScreen()));
_selectedIndex = 0;
} else {
Navigator.push(
context, MaterialPageRoute(builder: (context) => Councils()));
_selectedIndex = 1;
}

但这似乎行不通。我不知道该怎么做。

最佳答案

_selectedIndex 与 PageView 一起使用,并像这样设置 onTap :

          currentIndex: _selectedIndex,
selectedItemColor: Colors.grey[900],
unselectedItemColor: Colors.grey[50],
onTap: (int index) {
setState(()=>_selectedIndex=index);
}

阅读此 article会有帮助

编辑:这是一个完整的例子

class MyHomePage extends StatefulWidget {
MyHomePage({
Key? key,
}) : super(key: key);

@override
State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
int _selectedIndex = 0;
late PageController _pageController;
@override
void initState() {
super.initState();
_pageController = PageController(
initialPage: _selectedIndex,
);
}

Widget build(BuildContext context) {
return Scaffold(
bottomNavigationBar: BottomNavigationBar(
currentIndex: _selectedIndex,
onTap: (index) {
setState(() {
_selectedIndex = index;
_pageController.animateToPage(index,
duration: Duration(milliseconds: 500), curve: Curves.ease);
});
},
items: [
BottomNavigationBarItem(
icon: Icon(Icons.home),
label: "Home",
),
BottomNavigationBarItem(
icon: Icon(Icons.search),
label: "Search",
),
],
),
appBar: AppBar(
title: Text('Test App'),
),
body: PageView(
controller: _pageController,
onPageChanged: (index) {
setState(() {
_selectedIndex = index;
});
},
children: [
Container(
color: Colors.red,
child: Center(
child: Text("Home"),
),
),
Container(
color: Colors.green,
child: Center(
child: Text("Search"),
),
),
],
));
}
}

关于flutter - 我应该如何在导航到另一个屏幕时更改 BottomNavigationBar 的 currentIndex 属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71100660/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com