flutter - 如何有条件地将孩子添加到孩子列表中?
问题描述
我正在尝试创建一个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()
,
),
想知道是否有像拳头方法这样的内联方式来做到这一点。
解决方案
您可以使用三元运算符。
[条件==真?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 小部件。
推荐阅读
- python - 如何在 django 中过滤具有日期范围的查询
- java - 如何在 Java 方法中返回值?
- c# - 如何使碰撞在 Unity2D 中正常工作?
- javascript - 如何通过 JS 或 JQuery 删除 html 中的代码
- uwp - Windows 10 开发者设置中的 PIN 码在哪里?
- c# - 仪表板背景图。网络mvc核心
- c++ - 链接库和头文件 g++
- powershell - Invoke-Command 在本地运行时是在当前范围内运行还是在子范围内运行?
- java - 如何直接从复制或分享 URL 中获取 Instagram 图片或视频 URL?
- c++ - std::make_unique 带有空指针?