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

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语句,可以使用Flutter Visibility小部件

在这里查看文档

其他回答

仅当部件振动时

if(bool = true) Container(

child: ....

),

OR

if(bool = true) Container(

child: ....

) else new Container(child: lalala),

****您还可以使用此方法****来使用条件

 int _moneyCounter = 0;
  void _rainMoney(){
    setState(() {
      _moneyCounter +=  100;
    });
  }

new Expanded(
          child: new Center(
            child: new Text('\$$_moneyCounter', 

            style:new TextStyle(
              color: _moneyCounter > 1000 ? Colors.blue : Colors.amberAccent,
              fontSize: 47,
              fontWeight: FontWeight.w800
            )

            ),
          ) 
        ),
child: Container(
   child: isFile == true ? 
            Image.network(pathfile, width: 300, height: 200, fit: BoxFit.cover) : 
            Text(message.subject.toString(), style: TextStyle(color: Colors.white),
      ),
),

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

我发现使用条件逻辑构建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),
      ],
    );
  },
);

非常整洁,因为你可以在几个小部件中重用你的颜色选择器函数。