【发布时间】:2020-11-13 00:32:02
【问题描述】:
我有一个 Flutter 应用程序,它使用 BottomNavigationBar。我创建了一个名为CustomBottomNavBar 的类,它描述了我的BottomNavigationBar。在那里,我有一个名为currentIndex 的整数字段,它是导航栏上当前选定图标的索引。我想从我的 main.dart 类中获取这个值,以显示名为 tabs 的list<Widget> 的索引元素,其中包含相关的选项卡。
CustomNavigationBar 类:
class CustomBottomNavBar extends StatefulWidget {
@override
_CustomBottomNavBarState createState() => _CustomBottomNavBarState();
}
class _CustomBottomNavBarState extends State<CustomBottomNavBar> {
int currentIndex = 0;
@override
Widget build(BuildContext context) {
return SizedBox(
height: 50,
child: BottomNavigationBar(
type: BottomNavigationBarType.fixed,
selectedFontSize: 11,
unselectedFontSize: 11,
selectedItemColor: Colors.white,
backgroundColor: Colors.grey[850],
currentIndex: currentIndex,
items: <BottomNavigationBarItem>[
BottomNavigationBarItem(
activeIcon: Icon(Icons.home),
icon: Icon(
Icons.home,
color: currentIndex == 0 ? Colors.white : Colors.grey[500],
),
title: Text(
"Home",
style: TextStyle(color: currentIndex == 0 ? Colors.white : Colors.grey[500]),
),
),
BottomNavigationBarItem(
activeIcon: Icon(Icons.explore),
icon: Icon(
Icons.explore,
color: currentIndex == 1 ? Colors.white : Colors.grey[500],
),
title: Text(
"Explore",
style: TextStyle(color: currentIndex == 1 ? Colors.white : Colors.grey[500]),
)),
BottomNavigationBarItem(
activeIcon: Icon(Icons.subscriptions),
icon: Icon(Icons.subscriptions, color: currentIndex == 2 ? Colors.white : Colors.grey[500]),
title: Text(
"Subscriptions",
style: TextStyle(color: currentIndex == 2 ? Colors.white : Colors.grey[500]),
)),
BottomNavigationBarItem(
activeIcon: Icon(Icons.mail),
icon: Icon(
Icons.mail,
color: currentIndex == 3 ? Colors.white : Colors.grey[500],
),
title: Text(
"Inbox",
style: TextStyle(color: currentIndex == 3 ? Colors.white : Colors.grey[500]),
)),
BottomNavigationBarItem(
activeIcon: Icon(Icons.video_library),
icon: Icon(
Icons.video_library,
color: currentIndex == 4 ? Colors.white : Colors.grey[500],
),
title: Text(
"Library",
style: TextStyle(color: currentIndex == 4 ? Colors.white : Colors.grey[500]),
))
],
onTap: (int index) {
setState(() {
currentIndex = index;
});
},
),
);
}
}
main.dart:
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
final List<Widget> tabs = [
Center(child: Text("Home"),),
Center(child: Text("Explore"),),
Center(child: Text("Subscriptions"),),
Center(child: Text("Inbox"),),
Center(child: Text("Library"),),
];
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: CustomAppBar(),
body: tabs[2], //Here I would like to do something like tabs[customBottomNavBar.currentIndex]
//),
bottomNavigationBar: CustomBottomNavBar()),
);
}
}
【问题讨论】:
-
您可以将您的自定义索引传递给
CustomBottomNavBar,但我认为通常您可能希望返回并再次通过颤振导航教程。我认为你给自己造成了不必要的困难。一般来说,我建议给每个页面一个 ID,然后您可以检查底部导航栏以查看您的 ID 是否匹配以决定要突出显示的内容。
标签: flutter user-interface dart stateful