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

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


当前回答

更好的方法

 Column(
        children: [
            if (firstCondition == true) ...[
              DayScreen(),
            ] else if(secondCondition == true)...[
              StatsScreen(),
            ], else...[
              StatsScreen(),
            ],
        ],
     ),

其他回答

我不知道这是否是一个好的做法,但我正在使用:

class StatmentExample extends StatelessWidget {
  Widget build(BuildContext context) {
    return pageValue==1 ? Page1():pageValue== 2? Page2():pageValue==3 ? Page3():Page4();
  }
}

仅当部件振动时

if(bool = true) Container(

child: ....

),

OR

if(bool = true) Container(

child: ....

) else new Container(child: lalala),

在Flutter中,条件渲染可以通过附带条款包轻松完成。 它有一组全面的条件小部件和构建器,可以生成可读性更强、更简单的条件语句代码。

API和helper包括但不限于:

条件小部件和构建器:

ConditionWidget(
  condition: starred,
  widget: Icon(
    Icons.favorite
  ),
  fallback: fallbackWidget
)

ConditionBuilder(
  condition: (_) => someCondition,
  trueBuilder: (_) => trueWidget,
  fallbackBuilder: (_) => fallbackWidget
)

开关机箱条件:

SwitchCaseBuilder.widget<String>(
  context: context,
  condition: (_) => '1',
  caseBuilders: {'1': (_) => someWidget(), '2': (_) => someWidget()},
  fallbackBuilder: (_) => fallbackWidget,
);  

甚至是一个有条件的父小部件

ConditionalWrap(
  shouldWrap: shouldWrapChildInParent,
  child: Container(),
  parentBuilder: (child) => Container(
    child: child,
  ),
)

API支持单个或多个小部件呈现。 欢迎你试一试。

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

 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
            )

            ),
          ) 
        ),

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

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

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