【问题标题】:If case not working inside Widget [Flutter]如果小部件 [Flutter] 中的情况不起作用
【发布时间】:2018-12-25 03:35:51
【问题描述】:

我不能在 Widget 中写 if case 来选择要显示的 Container 吗?

我的代码:

return Card(
          child: Container(
              child: Row(
        children: <Widget>[
          Container(
              width: 50.0,
              height: 50.0,
              decoration: new BoxDecoration(
                  shape: BoxShape.circle,
                  image: new DecorationImage(
                      fit: BoxFit.fill,
                      image: new NetworkImage(
                          hits[index]["b"]["c"])))),
          hits[index]["f"] == null
              ? Container(
                  child: Text("if"),
                )
              : Container(
                  child: Text("else"),
                )
        ],
      )));

当我做类似 up 的事情时,它会立即出错。

错误:

flutter:抛出了另一个异常: 'package:flutter/src/widgets/text.dart':断言失败:第 213 行 pos 15: 'data != null': 不正确。

【问题讨论】:

  • “它给出了即时错误。”看到该错误对于诊断问题至关重要 - 所以请将其添加到您的问题中。
  • 更新问题
  • 我不知道这个错误是否与此有关,因为我看到的唯一错误日志是我添加到问题中的那个
  • 是的,你可以进行条件渲染,错误似乎与这段代码无关。
  • @HemanthRaj 你能举个例子作为答案吗?

标签: flutter


【解决方案1】:

应该可以,你可以在flutter中进行条件渲染。

例子:

Card(
    child: Container(
      child: Row(
        children: <Widget>[
          Container(
            width: 50.0,
            height: 50.0,
            color: Colors.red,
          ),
          data == null
              ? Container(
                  child: Text("if"),
                )
              : Container(
                  child: Text("else"),
                )
        ],
      ),
    ),
  ),

希望这会有所帮助!

【讨论】:

  • 我在做同样的事情
  • 谢谢你成功了,但我不知道为什么,因为我在做的是一样的
  • 问题是它没有进入 else 状态,因为在迭代之后有一些不为空的东西
  • 尝试调用 setState
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-07-11
  • 1970-01-01
  • 2021-07-29
  • 2020-08-16
  • 2019-12-21
  • 1970-01-01
  • 2020-10-10
相关资源
最近更新 更多