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

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或开关语句而不颤振认为有死代码?


当前回答

在Dart中,if/else和switch是语句而不是表达式。它们不返回值,所以不能将它们传递给构造函数参数。如果您的构建方法中有很多条件逻辑,那么尝试简化它是一个很好的实践。例如,您可以将自包含逻辑移动到方法,并使用if/else语句来初始化稍后使用的局部变量。

使用方法和if/else

Widget _buildChild() {
  if (condition) {
    return ...
  }
  return ...
}

Widget build(BuildContext context) {
  return new Container(child: _buildChild());
}

使用if/else

Widget build(BuildContext context) {
  Widget child;
  if (condition) {
    child = ...
  } else {
    child = ...
  }
  return new Container(child: child);
}

其他回答

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

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

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

在这种情况下,我建议使用三元操作符:

条件?Container(): Center()

并尽量避免使用如下形式的代码:

if (condition)返回A否则返回B

这比三元运算符更冗长。

但如果需要更多的逻辑,你还可以:

使用Builder小部件

Builder小部件是为了允许在需要子小部件时使用闭包:

一个柏拉图式的小部件,它调用闭包来获取它的子小部件。

任何时候你需要逻辑来构建小部件都很方便,它避免了创建专用函数的需要。

你使用Builder小部件作为子组件,你在它的Builder方法中提供你的逻辑:

Center(
  child: Builder(
    builder: (context) {
      // any logic needed...
      final condition = _whateverLogicNeeded();
      
      return condition
          ? Container();
          : Center();
    }
  )
)

Builder为保存创建逻辑提供了一个方便的地方。它比atreeon提出的直接匿名函数更直接。

我也同意逻辑应该从UI代码中提取出来,但当它真的是UI逻辑时,有时保留它更容易读懂。

如果你使用小部件列表,你可以使用这个:

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(),
      )),
    );
  }
}

如果你想在Text()小部件中使用If语句,你可以像这样使用匿名函数:

class ConditionalStatmentExample extends StatelessWidget {
  Widget build(BuildContext context) {
    return Text(
     (() {
      if(true){
        return "return a string";
      }

      return "any other string when the condition is not met";
     })(),
     textAlign: TextAlign.center, );
  }
}

仅当部件振动时

if(bool = true) Container(

child: ....

),

OR

if(bool = true) Container(

child: ....

) else new Container(child: lalala),