【问题标题】:How to omit second condition如何省略第二个条件
【发布时间】:2020-08-17 15:18:12
【问题描述】:

如何在条件语句中省略第二个条件?

    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        message != null
            ? Padding(
                padding: const EdgeInsets.all(24.0),
                child: Text(message),
              )
            : null, // how to omit second condition?
      ],
    );

如果第二个条件是 null 我得到了

════════ 小部件库捕获的异常════════ 在构建 ExportData(dirty, state: _ExportDataState#e723d): 列的子项不得包含任何空值,但在索引 4 处发现空值

【问题讨论】:

  • children: [ if (message != null) Padding(...), ...]
  • @pskink 你认为它在语法上是有效的 Dart 吗?
  • @bereal 是的,我认为
  • @bereal 查看dart.dev/guides/language/language-tour 并输入^F promoActive
  • @bereal 仓促?什么仓促?您只是好奇...顺便说一句,您也可以使用for 循环...

标签: flutter dart


【解决方案1】:

我更喜欢SizedBox 而不是Container

return Column(
  mainAxisAlignment: MainAxisAlignment.center,
  children: <Widget>[
    message != null
        ? Padding(
            padding: const EdgeInsets.all(24.0),
            child: Text(message),
          )
        : SizedBox(),
  ],
);

【讨论】:

  • 只是好奇 - 使用 sizedbox 比容器有什么优势?
  • 看到这个链接兄弟stackoverflow.com/a/57703904/4608334@Mahori
  • 我倾向于同意这个选项,我们也可以将 const 与 SizedBox 一起使用。
  • @VinothVino 感谢您的链接。我也将开始使用 sizedBox 作为占位符!
  • 很好,使用 SizedBox +1 :)
【解决方案2】:

在这种情况下,通常我会返回一个 Container()。


return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        message != null
            ? Padding(
                padding: const EdgeInsets.all(24.0),
                child: Text(message),
              )
            : Container(), // how to omit second condition?
      ],
    );

【讨论】:

    猜你喜欢
    • 2011-07-13
    • 2018-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-19
    • 1970-01-01
    相关资源
    最近更新 更多