到目前为止,当我需要在小部件中使用条件语句时,我已经做了以下工作(使用中心和容器作为简化的虚拟示例):
new Center(
child: condition == true ? new Container() : new Container()
)
虽然当我尝试使用if/else语句时,它会导致一个死亡代码警告:
new Center(
child:
if(condition == true){
new Container();
}else{
new Container();
}
)
有趣的是,我尝试了一个switch case语句,它给了我同样的警告,因此我不能运行代码。我做错了什么,或者它是这样的,不能使用if/else或开关语句而不颤振认为有死代码?
我个人使用if/else语句在子语句中使用这种block语句。它只支持Dart 2.3.0以上版本。
If / else
Column(
children: [
if (_selectedIndex == 0) ...[
DayScreen(),
] else ...[
StatsScreen(),
],
],
),
If / else If
Column(
children: [
if (_selectedIndex == 0) ...[
DayScreen(),
] else if(_selectedIndex == 1)...[
StatsScreen(),
],
],
),
多部件示例
Column(
children: [
if (_selectedIndex == 0) ...[
DayScreen(),
AboutScreen(),
InfoScreen(),
] else if(_selectedIndex == 1)...[
HomeScreen(),
StatsScreen(),
],
],
),