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

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小部件

在这里查看文档

其他回答

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

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

像这样做

Widget showIf(bool shouldShow, Widget widget) {
if (shouldShow) {
  return widget;
} else {
  return Container();
}}

所以当你想用条件来展示某物的时候你会说

Column(children: [showIf(myConditionIsTrue, myComplexWidget)])

编辑:我不再推荐我在下面发布的解决方案,因为我意识到使用这种方法,生成了真实结果的子结果和虚假结果的子结果,但只使用了一个,这不必要地降低了代码的速度。


之前的回答:

在我的应用程序中,我创建了一个WidgetChooser小部件,这样我就可以在没有条件逻辑的小部件之间进行选择:

WidgetChooser(
      condition: true,
      trueChild: Text('This widget appears if the condition is true.'),
      falseChild: Text('This widget appears if the condition is false.'),
    );

这是WidgetChooser小部件的源代码:

import 'package:flutter/widgets.dart';

class WidgetChooser extends StatelessWidget {
  final bool condition;
  final Widget trueChild;
  final Widget falseChild;

  WidgetChooser({@required this.condition, @required this.trueChild, @required this.falseChild});

  @override
  Widget build(BuildContext context) {
    if (condition) {
      return trueChild;
    } else {
      return falseChild;
    }
  }
}

另一种选择:对于“switch’s”这样的语句,有很多条件,我喜欢使用map:

return Card(
        elevation: 0,
        margin: EdgeInsets.all(1),
        child: conditions(widget.coupon)[widget.coupon.status] ??
            (throw ArgumentError('invalid status')));


conditions(Coupon coupon) => {
      Status.added_new: CheckableCouponTile(coupon.code),
      Status.redeemed: SimpleCouponTile(coupon.code),
      Status.invalid: SimpleCouponTile(coupon.code),
      Status.valid_not_redeemed: SimpleCouponTile(coupon.code),
    };

在不使用条件语句的情况下,更容易向条件列表中添加/删除元素。

另一个例子:

var condts = {
  0: Container(),
  1: Center(),
  2: Row(),
  3: Column(),
  4: Stack(),
};

class WidgetByCondition extends StatelessWidget {
  final int index;
  WidgetByCondition(this.index);
  @override
  Widget build(BuildContext context) {
    return condts[index];
  }
}