如何有条件地将孩子添加到孩子列表中?

问题描述 投票:0回答:3

我正在尝试创建一个ListTile,我希望有2个孩子作为字幕。仅当不为null时,才应添加子项。

 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()
        ,
      ),

想知道是否有拳头方法之类的内联方法来执行此操作。

flutter flutter-layout
3个回答
0
投票

您可以使用最近添加的列表操作。

  subtitle: Row(
    children: [
      if (attachment.prop1 != null) Text(attachment.prop1), 
      if (attachment.prop2 != null) Text(attachment.prop2), 
    ],
  ),

0
投票

您可以在列表中使用条件三元运算符

 ListTile(
  title: Text(attachment.title),
  subtitle: Row(
    children: [
      prop1 == null ? Text(attachment.prod2) : Text(attachment.prop1),
    ],
  ),

0
投票

您可以使用三元运算符。

[条件== true?如果为true,则添加部件1:如果为false,则添加部件2,]

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

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

注意:对于其他情况,您必须传递一个空的Container()小部件。否则您的应用将抛出错误。

© www.soinside.com 2019 - 2024. All rights reserved.