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

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


当前回答

我更喜欢使用Map<String, Widget>

Map<String, Widget> pageSelector = {
"login": Text("Login"),
"home": Text("Home"),
}

在build函数中,我像这样将键传递给map

new Center(
 child: pageSelector["here pass the key"] ?? Text("some default widget"),
)

或者另一种解决方案是使用简单的函数

Widget conditionalWidget(int numberToCheck){
 switch(numberToCheck){
   case 0: return Text("zero widget");
   case 1: return Text("one widget");
   case 2: return Text("two widget");
   case 3: return Text("three widget");
   default: return Text("default widget");
}

在构建函数中传递要检查的小部件的编号或任何其他参数

new Center(
 child: conditionalWidget(pageNumber),
)

其他回答

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

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

最简单的方法:

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

这是解决方案。 我已经修好了。下面是代码

child: _status(data[index]["status"]),

Widget _status(status) {
  if (status == "3") {
    return Text('Process');
  } else if(status == "1") {
    return Text('Order');
  } else {
    return Text("Waiting");
  }
}

如果你想在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, );
  }
}

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

 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
            )

            ),
          ) 
        ),