到目前为止,当我需要在小部件中使用条件语句时,我已经做了以下工作(使用中心和容器作为简化的虚拟示例):

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(bool = true) Container(

child: ....

),

OR

if(bool = true) Container(

child: ....

) else new Container(child: lalala),

其他回答

这是一篇很棒的文章和对话。我尝试使用如上所述的三元运算符。但是代码没有工作,导致了前面提到的错误。

Column(children: [ condition? Text("True"): null,],);

上面的三元例子是miss leading。Dart将响应一个错误,返回的是null而不是小部件。你不能返回null。正确的方法是返回一个小部件:

Column(children: [ condition? Text("True"): Text("false"),],); 

为了让三元函数正常工作,您需要返回一个Widget。如果你不想返回任何东西,你可以返回一个空容器。

Column(children: [ condition? Text("True"): Container(),],); 

祝你好运。

最简单的方法:

// 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(...),
],

像这样做

Widget showIf(bool shouldShow, Widget widget) {
if (shouldShow) {
  return widget;
} else {
  return Container();
}}

所以当你想用条件来展示某物的时候你会说

Column(children: [showIf(myConditionIsTrue, myComplexWidget)])

您可以在以下操作中使用builder: 我已经考虑了一个条件,我们可以得到图像url为空,因此,如果为空,我显示一个缩小大小的盒子,因为它没有一个完全无效的小部件的属性。

Builder(builder: (BuildContext context) {
  if (iconPath != null) {
    return ImageIcon(
      AssetImage(iconPath!),
      color: AppColors.kPrimaryColor,
    );
  } else {
    return SizedBox.shrink();
  }
})

为了记录,Dart 2.3增加了在Collection字面量中使用if/else语句的能力。这是现在完成以下方式:

return Column(children: <Widget>[
  Text("hello"),
  if (condition)
     Text("should not render if false"),
  Text("world")
],);

颤振问题#28181 -内联条件渲染列表