到目前为止,当我需要在小部件中使用条件语句时,我已经做了以下工作(使用中心和容器作为简化的虚拟示例):
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或开关语句而不颤振认为有死代码?
在我看来,最好和最干净的方式,我更喜欢的是创建一个helper类型定义函数类coditional_widget.dart。
typedef IfWidget = List<Widget> Function(bool, Widget);
typedef IfElseWidget = Widget Function(bool, Widget, Widget);
typedef ElseEmptyWidget = Widget Function(bool, Widget);
IfWidget ifTrueWidget =
(bool condition, Widget child) => [if (condition) child];
IfElseWidget ifElseWidget =
(bool condition, Widget isTrueChild, Widget isFalseChild) =>
condition ? isTrueChild : isFalseChild;
ElseEmptyWidget elseEmptyWidget = (bool condition, Widget isTrueChild) =>
condition ? isTrueChild : const SizedBox.shrink();
如何使用
// IfWidget
** Row/ Column / Wrap child etc.
children: <Widget>[
...ifWidget(title != null, Text('Only Display for True Conditon')),
]
// elseEmptyWidget
** Row/ Column / Wrap child etc.
children: <Widget>[
elseEmptyWidget(title!=null,Text('Only Display for True Conditon')),
]
// ifElseWidget
** Row/ Column / Wrap child etc.
children: <Widget>[
ifElseWidget(true,Text('Only Display for True Conditon'),Text('Only Display for false Conditon')),
]
这只是几个你可以添加更多的
实际上,你可以在dart / flutter中使用if/else和switch以及任何其他语句。
使用立即匿名函数
class StatmentExample extends StatelessWidget {
Widget build(BuildContext context) {
return Text((() {
if(true){
return "tis true";}
return "anything but true";
})());
}
}
即把你的语句包装在一个函数中
(() {
// your code here
}())
我强烈建议不要把太多的逻辑直接放在你的UI“标记”上,但我发现Dart中的类型推断需要一些工作,所以它有时在这种情况下很有用。
使用三元运算符
condition ? Text("True") : null,
在集合中使用If或For语句或展开运算符
children: [
...manyItems,
oneItem,
if(canIKickIt)
...kickTheCan
for (item in items)
Text(item)
使用方法
child: getWidget()
Widget getWidget() {
if (x > 5) ...
//more logic here and return a Widget
重定义switch语句
作为三元操作符的另一种选择,您可以创建switch语句的函数版本,例如下面的帖子https://stackoverflow.com/a/57390589/1058292。
child: case2(myInput,
{
1: Text("Its one"),
2: Text("Its two"),
}, Text("Default"));
有两种可能:
如果您只使用一个小部件
解决方案= >
Visibility(
visible: condition == true,
child: Text(""),
),
OR
Offstage(
offstage: condition == false,
child: Text(""),
),
如果您正在使用两个或更多小部件
解决方案= >
bool _visibility = false;
isVisible?
Widget1
:
WIdget2