You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Card中展示Patients类内ListNote列表的元素?

解决方案

要读取并展示嵌套在Patients中的ListNote列表,你需要处理可空列表的空值判断,同时遍历列表生成对应的Card组件。以下是修正后的代码:

完整的_body()方法实现

_body() {
  // 处理listOfNotes的空值,避免空指针异常
  final notes = widget.patients.listOfNotes ?? [];

  return Column(
    children: <Widget>[
      Expanded(
        child: ListView(
          children: notes.map((note) {
            return Card(
              margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // 展示标题,为空时显示默认文本
                    Text(
                      note.title ?? '无标题',
                      style: const TextStyle(
                        fontSize: 18,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    const SizedBox(height: 8),
                    // 展示笔记内容
                    Text(note.note ?? '无内容'),
                    const SizedBox(height: 8),
                    // 展示结论
                    Text(
                      note.conclusion ?? '无结论',
                      style: const TextStyle(color: Colors.grey),
                    ),
                  ],
                ),
              ),
            );
          }).toList(),
        ),
      ),
    ],
  );
}

关键说明

  • 空值处理:用widget.patients.listOfNotes ?? []确保即使列表为空,也能返回一个空列表,避免空指针异常。
  • 遍历列表:通过map()方法将每个ListNote对象转换为Card组件,再用toList()生成ListView的子组件列表。
  • 字段展示:每个字段(title/note/conclusion)都用??处理空值,保证UI不会因为空字段崩溃。
  • UI优化:添加了内边距、外边距和文本样式,让Card的展示更美观。

内容的提问来源于stack exchange,提问作者Buubulle

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 19:25:41