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

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


当前回答

简单的方法:

使用Builder小部件

Center(
    child: Builder(
        builder: (context) {
        if (a == b) {
          return const Widget1();
        } else {
          return const Widget2();
         }
        },
   ),
)

其他回答

在我看来,最好和最干净的方式,我更喜欢的是创建一个helper类型定义函数类coditional_widget.dart。

typedef IfWidget = List<Widget> Function(bool, Widget);
typedef IfElseWidget = Widget Function(bool, Widget, Widget);
typedef ElseEmptyWidget = Widget Function(bool, Widget);

IfWidget ifTrueWidget =
    (bool condition, Widget child) => [if (condition) child];

IfElseWidget ifElseWidget =
    (bool condition, Widget isTrueChild, Widget isFalseChild) =>
        condition ? isTrueChild : isFalseChild;

ElseEmptyWidget elseEmptyWidget = (bool condition, Widget isTrueChild) =>
    condition ? isTrueChild : const SizedBox.shrink();

如何使用

// IfWidget 
  ** Row/ Column / Wrap child etc.
   children: <Widget>[
      ...ifWidget(title != null, Text('Only Display for True Conditon')),
      ]

// elseEmptyWidget
  ** Row/ Column / Wrap child etc.
   children: <Widget>[
          
      elseEmptyWidget(title!=null,Text('Only Display for True Conditon')),
      ]



// ifElseWidget
      ** Row/ Column / Wrap child etc.
       children: <Widget>[
            ifElseWidget(true,Text('Only Display for True Conditon'),Text('Only Display for false Conditon')),
          ]

这只是几个你可以添加更多的

我更喜欢使用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),
)

有一个按钮

bool _paused = false;

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

您可以在以下操作中使用builder: 我已经考虑了一个条件,我们可以得到图像url为空,因此,如果为空,我显示一个缩小大小的盒子,因为它没有一个完全无效的小部件的属性。

Builder(builder: (BuildContext context) {
  if (iconPath != null) {
    return ImageIcon(
      AssetImage(iconPath!),
      color: AppColors.kPrimaryColor,
    );
  } else {
    return SizedBox.shrink();
  }
})

如果希望避免使用If语句,可以使用Flutter Visibility小部件

在这里查看文档