我有一个自定义导航栏的问题。我无法更改正文中的页面。我把4个不同的文本用于测试。后来我想要有不同页面的somo小部件。 _buildItem位于不同的小部件中,但位于同一页面中。
class InicioPage extends StatefulWidget {
final int selectedIndex = 0;
@override
State<StatefulWidget> createState() {
return InicioPageState(selectedIndex);
}
}
class InicioPageState extends State<InicioPage> {
int selectedIndex;
InicioPageState(this.selectedIndex);
final pages = [Text('page 0'),Text('page 1'), ];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
elevation: 1,
title: Text('Title of App'), ),
bottomNavigationBar: BottomNavBar(selectedIndex),
body: pages[selectedIndex], ); } }
这是导航栏。我切了一些不重要的部分,因为这些字符。
class BottomNavBar extends StatefulWidget {
final int selectedIndex;
BottomNavBar(this.selectedIndex);
@override
State<StatefulWidget> createState() {
return BottomNavBarState(selectedIndex);
},}
class BottomNavBarState extends State<BottomNavBar> {
int selectedIndex;
BottomNavBarState(this.selectedIndex);
List<NavigationItem> items = [
NavigationItem(Icon(Icons.home), Text('Home')),
NavigationItem(Icon(Icons.location_city), Text('Props')),
];
@override
Widget build(BuildContext context) {
return Container(
child: Row(
children: items.map((item) { var itemIndex = items.indexOf(item);
return GestureDetector( onTap: () { setState(() {
selectedIndex = itemIndex;
}); },
child: _buildItem(item, selectedIndex == itemIndex),
);
}).toList(),
));
}
}
不要通过构造函数在BottomNavBarState中传递params,只需使用
widget.selectedIndex