如何有条件地显示BottomNavigationBar
答案 0 :(得分:1)
没有else
大小写,就不能使用三元运算符。
由于三元运算符由?:
组成,因此您不能选择不使用其中一个。
OP的问题:“那么,如果我只需要单独使用if()条件,该怎么办?”
只需:
Widget _someWidget() {
if (condition) {
return doSomething
}
return doSomethingElse
}
根据您要执行的操作,可以使用如下三元运算符:
condition ? doSomething : null
答案 1 :(得分:1)
要有条件地显示BottomNavBar ,您可以检查条件,如果条件为true,则为bottomNavigationBar
字段提供属性,否则为null。
bottomNavigationBar: conditionTrue ? BottomNavigationBar(
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Padding(
padding: EdgeInsets.all(0),
),
title: Text('One'),
),
BottomNavigationBarItem(
icon: Padding(
padding: EdgeInsets.all(0),
),
title: Text('Two'),
),
BottomNavigationBarItem(
icon: Padding(
padding: EdgeInsets.all(0),
),
title: Text('Three'),
),
],
currentIndex: _currentIndex,
selectedItemColor: Theme.of(context).primaryColor,
onTap: _onItemTapped,
showSelectedLabels: true,
showUnselectedLabels: true,
selectedFontSize: 16,
type: BottomNavigationBarType.fixed,
unselectedItemColor: Colors.black,
) : null, //give it a null if the condition is not met...
如果要有条件隐藏BottomNavigationBarItem:
第1步:定义一个列表,其中包含要最初显示为的BottomNavigationBarItems:
List<BottomNavigationBarItem> items = <BottomNavigationBarItem>[
BottomNavigationBarItem(
// icon: Icon(null),
icon: Padding(
padding: EdgeInsets.all(0),
),
title: Text('One'),
),
BottomNavigationBarItem(
icon: Padding(
padding: EdgeInsets.all(0),
),
title: Text('Two'),
),
BottomNavigationBarItem(
icon: Padding(
padding: EdgeInsets.all(0),
),
title: Text('Three'),
),
];
第2步:将此项目列表作为参数传递给BottomNavigationBar构造函数中的items参数,如下所示:
bottomNavigationBar: BottomNavigationBar( //remove the const keyword from here in your code too.
items: items,
currentIndex: _currentIndex,
selectedItemColor: Theme.of(context).primaryColor,
onTap: _onItemTapped,
showSelectedLabels: true,
showUnselectedLabels: true,
selectedFontSize: 16,
type: BottomNavigationBarType.fixed,
unselectedItemColor: Colors.black,
),
第3步:在代码中的任意位置设置项目列表的状态,以更改列表中的项目。
出于演示目的,每当您单击“浮动动作”按钮时,我都会更改状态。您可以在代码中的任何地方实现此类功能。
floatingActionButton: FloatingActionButton(
onPressed: () {
setState(() {
items.removeAt(0);
});
},