到目前为止,当我需要在小部件中使用条件语句时,我已经做了以下工作(使用中心和容器作为简化的虚拟示例):
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或开关语句而不颤振认为有死代码?
另一种选择:对于“switch’s”这样的语句,有很多条件,我喜欢使用map:
return Card(
elevation: 0,
margin: EdgeInsets.all(1),
child: conditions(widget.coupon)[widget.coupon.status] ??
(throw ArgumentError('invalid status')));
conditions(Coupon coupon) => {
Status.added_new: CheckableCouponTile(coupon.code),
Status.redeemed: SimpleCouponTile(coupon.code),
Status.invalid: SimpleCouponTile(coupon.code),
Status.valid_not_redeemed: SimpleCouponTile(coupon.code),
};
在不使用条件语句的情况下,更容易向条件列表中添加/删除元素。
另一个例子:
var condts = {
0: Container(),
1: Center(),
2: Row(),
3: Column(),
4: Stack(),
};
class WidgetByCondition extends StatelessWidget {
final int index;
WidgetByCondition(this.index);
@override
Widget build(BuildContext context) {
return condts[index];
}
}
你可以简单地使用条件语句a==b?c: d
例如:
Container(
color: Colors.white,
child: ('condition')
? Widget1(...)
: Widget2(...)
)
我希望你明白了。
假设如果没有其他条件,你可以使用sizebox .shrink()
Container(
color: Colors.white,
child: ('condition')
? Widget1(...)
: SizedBox.shrink()
)
如果是列,不需要写?:运算符
Column(
children: <Widget>[
if('condition')
Widget1(...),
],
)
最简单的方法:
// the ternary operator:
<conditon>
? Widget1(...)
: Widget2(...)
// Or:
if (condition)
Widget1(...)
// With else/ if else
if (condition1)
Widget1(...)
else if (condition2)
Widget2(...)
else
Widget3(...),
如果你想在一个条件下呈现多个小部件,你可以使用扩展操作符(为此,你必须在行,列或堆栈小部件中):
if (condition) ...[
Widget1(...),
Widget2(...),
],
// with else / else if:
if (condition1) ...[
Widget1(...),
Widget2(...),
]
else if(condition2)...[
Widget3(...),
Widget4(...),
]
else ...[
Widget3(...),
Widget4(...),
],
我个人使用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(),
],
],
),
如果你使用小部件列表,你可以使用这个:
class HomePage extends StatelessWidget {
bool notNull(Object o) => o != null;
@override
Widget build(BuildContext context) {
var condition = true;
return Scaffold(
appBar: AppBar(
title: Text("Provider Demo"),
),
body: Center(
child: Column(
children: <Widget>[
condition? Text("True"): null,
Container(
height: 300,
width: MediaQuery.of(context).size.width,
child: Text("Test")
)
].where(notNull).toList(),
)),
);
}
}