这是我的底部导航栏,现在我想显示底部导航栏,但最初没有选择它的任何项目。当我将_selectedIndex设置为 null 时,我收到错误。 有什么方法可以做到这一点吗?
int _selectedIndex = 0;
BottomNavigationBar(
backgroundColor: Colors.blueAccent,
unselectedItemColor: Colors.white,
items: [
BottomNavigationBarItem(
icon: Icon(Icons.add),
title: Text(''),
),
BottomNavigationBarItem(
icon: Icon(Icons.camera_alt),
title: Text(''),
),
BottomNavigationBarItem(
icon: Icon(Icons.person),
title: Text(''),
),
],
currentIndex: _selectedIndex,
onTap: (index) {
setState(() {
_selectedIndex = index;
});
},
);
// set default unselected
int _selectedIndex = -1;
BottomNavigationBar(
backgroundColor: Colors.blueAccent,
unselectedItemColor: Colors.white,
// if unselected change color to unselectedItemColor
selectedItemColor: (_selectedIndex != -1) ? Colors.grey : Colors.white,
items: [
BottomNavigationBarItem(
icon: Icon(Icons.add),
title: Text(''),
),
BottomNavigationBarItem(
icon: Icon(Icons.camera_alt),
title: Text(''),
),
BottomNavigationBarItem(
icon: Icon(Icons.person),
title: Text(''),
),
],
// if unselected change select index to 0, else you will get error
currentIndex: (_selectedIndex != -1) ? _selectedIndex : 0,
onTap: (index) {
setState(() {
_selectedIndex = index;
});
},
);
- 将初始或未选择定义为 -1
- 配置
selected
方法以在状态更改为-1
时进行更改
currentIndex: state.tabIndex == -1 ? 0 : state.tabIndex,
showSelectedLabels: state.tabIndex == -1 ? false : true,