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

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

问题描述

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

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 / else switch 以及任何其他内联语句

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

即用函数包装语句

(() {
  // 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


重新定义开关语句


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

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

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

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