如何在 Flutter 小部件(中心小部件)的子属性中使用条件语句 [英] How to use conditional statement within child attribute of a Flutter Widget (Center Widget)

查看:32
本文介绍了如何在 Flutter 小部件(中心小部件)的子属性中使用条件语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

到目前为止,每当我需要在小部件中使用条件语句时,我都会执行以下操作(使用中心和容器作为简化的虚拟示例):

So far whenever I needed to use a conditional statement within a Widget I have done the following (Using Center and Containers as simplified dummy examples):

new Center(
  child: condition == true ? new Container() : new Container()
)

虽然当我尝试使用 if/else 语句时,它会导致死代码警告:

Though when I tried using an if/else statement it would lead to an Dead code warning:

new Center(
  child: 
    if(condition == true){
      new Container();
    }else{
      new Container();
    }
)

有趣的是,我尝试了 switch case 语句,它给了我同样的警告,因此我无法运行代码.我是不是做错了什么,或者是因为我不能使用 if/else 或 switch 语句而不觉得有死代码?

Interestingly enough I tried with a switch case statement and it gives me the same warning and thus I cannot run the code. Am I doing something wrong or is it so that one cannot use if/else or switch statements without flutter thinking there is dead code?

推荐答案

实际上你可以使用 if/elseswitch 和任何其他dart/flutter 中的内联语句.

Actually you can use if/else and switch and any other statement inline in dart / flutter.

class StatmentExample extends StatelessWidget {
  Widget build(BuildContext context) {
    return Text((() {
      if(true){
        return "tis true";}

      return "anything but true";
    })());
  }
}

即将你的语句包装在一个函数中

ie wrap your statements in a function

(() {
  // your code here
}())

我强烈建议不要将过多的逻辑直接放在您的 UI标记"中,但我发现 Dart 中的类型推断需要一些工作,因此它有时在此类场景中很有用.

condition ? Text("True") : null,

在集合中使用 If 或 For 语句或扩展运算符

children: [
  ...manyItems,
  oneItem,
  if(canIKickIt)
    ...kickTheCan
  for (item in items)
    Text(item)

使用方法

child: getWidget()

Widget getWidget() {
  if (x > 5) ...
  //more logic here and return a Widget

重新定义switch语句

作为三元运算符的另一种替代方法,您可以创建 switch 语句的函数版本,例如在以下帖子 https://stackoverflow.com/a/57390589/1058292.

  child: case2(myInput,
  {
    1: Text("Its one"),
    2: Text("Its two"),
  }, Text("Default"));

这篇关于如何在 Flutter 小部件(中心小部件)的子属性中使用条件语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆