首页 > 解决方案 > 如何有条件地将孩子添加到孩子列表中?

问题描述

我正在尝试创建一个ListTile我想要有 2 个孩子作为字幕的地方。仅当不为空时才应添加子项。

 ListTile(
      title: Text(attachment.title),
      subtitle: Row(
        children: [
          Text(attachment.prop1), //Add only if prop1 is not null. How??
          Text(attachment.prod2), //Add only if prop2 is not null. How??
        ],
      ),

我可以通过编写函数 getChildren 然后使用以下内容来轻松做到这一点。

ListTile(
      title: Text(attachment.title),
      subtitle: Row(
        children: getChildren()
        ,
      ),

想知道是否有像拳头方法这样的内联方式来做到这一点。

标签: flutterflutter-layout

解决方案


您可以使用三元运算符。

[条件==真?if true add widget-1 : if false 添加 widget-2,]

在您的情况下,您可以像这样使用三元运算符,

[
  attachment.prop1 != null ? Text(attachment.prop1) : Container(), 
  attachment.prop2 != null ? Text(attachment.prod2) : Container(),
]

注意:如果您想遵循我的方法,则必须为“其他”情况传递一个空的 Container() 小部件。否则你的应用会抛出错误,因为 Flutter 不支持 null 小部件。


推荐阅读