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

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

    Builder(builder: (context) {
      /// some operation here ...
      if(someCondition) {
        return Text('A');
      }
      else {
        return Text('B');
      } 
    })
 

其他回答

除了三元操作符,如果需要在条件语句之前执行操作,还可以使用Builder小部件。

    Builder(builder: (context) {
      /// some operation here ...
      if(someCondition) {
        return Text('A');
      }
      else {
        return Text('B');
      } 
    })
 

有一个按钮

bool _paused = false;

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

简单的方法:

使用Builder小部件

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

Flutter Widget可以在不破坏代码树的情况下有条件地用父元素包装子树

import 'package:flutter/widgets.dart';

/// Conditionally wrap a subtree with a parent widget without breaking the code tree.
///
/// [condition]: the condition depending on which the subtree [child] is wrapped with the parent.
/// [child]: The subtree that should always be build.
/// [conditionalBuilder]: builds the parent with the subtree [child].
///
/// ___________
/// Usage:
/// ```dart
/// return ConditionalParentWidget(
///   condition: shouldIncludeParent,
///   child: Widget1(
///     child: Widget2(
///       child: Widget3(),
///     ),
///   ),
///   conditionalBuilder: (Widget child) => SomeParentWidget(child: child),
///);
/// ```
///
/// ___________
/// Instead of:
/// ```dart
/// Widget child = Widget1(
///   child: Widget2(
///     child: Widget3(),
///   ),
/// );
///
/// return shouldIncludeParent ? SomeParentWidget(child: child) : child;
/// ```
///
class ConditionalParentWidget extends StatelessWidget {
  const ConditionalParentWidget({
    Key key,
    @required this.condition,
    @required this.child,
    @required this.conditionalBuilder,
  }) : super(key: key);

  final Widget child;
  final bool condition;
  final Widget Function(Widget child) conditionalBuilder;

  @override
  Widget build(BuildContext context) {
    return condition ? this.conditionalBuilder(this.child) : this.child;
  }
}

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

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