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

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


当前回答

有一个按钮

bool _paused = false;

CupertinoButton(
  child: _paused ? Text('Play') : Text('Pause'),
  color: Colors.blue,
  onPressed: () {
    setState(() {
      _paused = !_paused;
    });
  },
),

其他回答

实际上,你可以在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"));

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

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

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

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

祝你好运。

我个人使用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(),
        ],
    ],
 ),

你可以简单地使用条件语句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(...),
 ],
)