到目前为止,当我需要在小部件中使用条件语句时,我已经做了以下工作(使用中心和容器作为简化的虚拟示例):
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或开关语句而不颤振认为有死代码?
我发现使用条件逻辑构建Flutter UI的一个简单方法是将逻辑保持在UI之外。下面是一个返回两种不同颜色的函数:
Color getColor(int selector) {
if (selector % 2 == 0) {
return Colors.blue;
} else {
return Colors.blueGrey;
}
}
下面的函数用于设置CircleAvatar的背景。
new ListView.builder(
itemCount: users.length,
itemBuilder: (BuildContext context, int index) {
return new Column(
children: <Widget>[
new ListTile(
leading: new CircleAvatar(
backgroundColor: getColor(index),
child: new Text(users[index].name[0])
),
title: new Text(users[index].login),
subtitle: new Text(users[index].name),
),
new Divider(height: 2.0),
],
);
},
);
非常整洁,因为你可以在几个小部件中重用你的颜色选择器函数。
你可以在dart中对条件语句使用三元运算符,它的使用很简单
(condition) ? statement1 : statement2
如果条件为真,则执行statement1,否则执行statement2。
举一个实际的例子
Center(child: condition ? Widget1() : Widget2())
请记住,如果您打算使用null作为Widget2,最好使用sizebox .shrink(),因为一些父部件将在获得null子部件后抛出异常。
我发现使用条件逻辑构建Flutter UI的一个简单方法是将逻辑保持在UI之外。下面是一个返回两种不同颜色的函数:
Color getColor(int selector) {
if (selector % 2 == 0) {
return Colors.blue;
} else {
return Colors.blueGrey;
}
}
下面的函数用于设置CircleAvatar的背景。
new ListView.builder(
itemCount: users.length,
itemBuilder: (BuildContext context, int index) {
return new Column(
children: <Widget>[
new ListTile(
leading: new CircleAvatar(
backgroundColor: getColor(index),
child: new Text(users[index].name[0])
),
title: new Text(users[index].login),
subtitle: new Text(users[index].name),
),
new Divider(height: 2.0),
],
);
},
);
非常整洁,因为你可以在几个小部件中重用你的颜色选择器函数。
编辑:我不再推荐我在下面发布的解决方案,因为我意识到使用这种方法,生成了真实结果的子结果和虚假结果的子结果,但只使用了一个,这不必要地降低了代码的速度。
之前的回答:
在我的应用程序中,我创建了一个WidgetChooser小部件,这样我就可以在没有条件逻辑的小部件之间进行选择:
WidgetChooser(
condition: true,
trueChild: Text('This widget appears if the condition is true.'),
falseChild: Text('This widget appears if the condition is false.'),
);
这是WidgetChooser小部件的源代码:
import 'package:flutter/widgets.dart';
class WidgetChooser extends StatelessWidget {
final bool condition;
final Widget trueChild;
final Widget falseChild;
WidgetChooser({@required this.condition, @required this.trueChild, @required this.falseChild});
@override
Widget build(BuildContext context) {
if (condition) {
return trueChild;
} else {
return falseChild;
}
}
}