我想BottomNavigationBar
在某些特定的屏幕/页面上使用,我不确定我是否做对了。我制作了一个小部件BottomNavBar
,并在我的页面/屏幕上实现了它。每当我单击时,假设Page3
它导航到Page3
但所选图标始终位于第一个图标按钮上,如下图所示。
我想到的是更改为所选屏幕/页面的图标按钮(汽车),在这种情况下Page 3
。总而言之,每当我从 BottomNavBar 中选择一个页面时,都应该选择相应的图标按钮并像上图一样突出显示蓝色。这是代码BottomNavBar
:
import 'package:flutter/material.dart';
import 'screens/page_1.dart';
import 'screens/page_2.dart';
import 'screens/page_3.dart';
import 'screens/page_4.dart';
import 'screens/page_5.dart';
class BottomNavBar extends StatefulWidget {
@override
_BottomNavBarState createState() => _BottomNavBarState();
}
class _BottomNavBarState extends State<BottomNavBar> {
int _selectedIndex = 0;
@override
Widget build(BuildContext context) {
return BottomNavigationBar(
backgroundColor: Colors.white,
currentIndex: _selectedIndex, // this will be set when a new tab is tapped
showUnselectedLabels: true,
onTap: (int index) {
setState(() {
_selectedIndex = index;
});
switch (index) {
case 0:
Navigator.pushNamed(context, Page1.id);
break;
case 1:
Navigator.pushNamed(context, Page2.id);
break;
case 2:
Navigator.pushNamed(context, Page3.id);
break;
case 3:
Navigator.pushNamed(context, Page4.id);
break;
case 4:
Navigator.pushNamed(context, Page5.id);
break;
}
},
type: BottomNavigationBarType.fixed,
items: [
BottomNavigationBarItem(
icon: Icon(Icons.dashboard),
label: "Page 1",
),
BottomNavigationBarItem(
icon: Icon(Icons.work),
label: "Page 2",
),
BottomNavigationBarItem(
icon: Icon(Icons.directions_car),
label: "Page 3",
),
BottomNavigationBarItem(
icon: Icon(Icons.supervised_user_circle),
label: "Page 4",
),
BottomNavigationBarItem(
icon: Icon(Icons.account_circle),
label: "Page 5",
),
],
);
}
}
以及 5 个相同页面/屏幕之一:
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'components/bottom_navigation_bar.dart';
class Page1 extends StatelessWidget {
static const String id = 'page_1';
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.white,
iconTheme: IconThemeData(
color: Colors.grey[600],
),
),
body: SafeArea(
child: Container(
child: Text('THIS IS PAGE 1'),
),
),
/// Here is where have I implemented the widget
bottomNavigationBar: BottomNavBar(),
);
}
}
这甚至是一个好方法吗?任何帮助表示赞赏,在此先感谢!