Flutter如何实现单个区块内展示日期、标题、内容三项文本数据
问题原因
- 当前代码在
ListView的children属性里写死了2个固定Card组件,仅1个组件绑定了单条博客数据,没有遍历整个listBlog数组,自然只能展示1条有效数据 - 代码中直接使用的
index变量没有在遍历作用域内定义,本身存在作用域报错风险 - 注释掉的
ListView.separated代码存在字段绑定错误:subtitle属性错误绑定了date字段,且没有外层Card容器,不符合三字段列布局的数据块展示要求
修正后可运行代码
@override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title), ), body: ListView( padding: const EdgeInsets.all(8), children: listBlog.map((blog) { return Card( margin: const EdgeInsets.symmetric(vertical: 6), child: Padding( padding: const EdgeInsets.all(12), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ // 日期字段:小字灰色 Text( blog.date, style: const TextStyle(color: Colors.grey, fontSize: 12), ), const SizedBox(height: 8), // 标题字段:加粗放大 Text( blog.title, style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold), ), const SizedBox(height: 6), // 内容字段:常规字号深灰色 Text( blog.content, style: const TextStyle(fontSize: 14, color: Colors.black87), ), ], ), ), ); }).toList(), ) // 长列表场景替换为下方ListView.separated实现,性能更优 /* body: ListView.separated( padding: const EdgeInsets.all(8), itemCount: listBlog.length, separatorBuilder: (_, __) => const SizedBox(height: 6), itemBuilder: (context, index) { final blog = listBlog[index]; return Card( child: Padding( padding: const EdgeInsets.all(12), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text(blog.date, style: const TextStyle(color: Colors.grey, fontSize: 12)), const SizedBox(height: 8), Text(blog.title, style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold)), const SizedBox(height: 6), Text(blog.content, style: const TextStyle(fontSize: 14, color: Colors.black87)), ], ), ), ); }, ) */ ); }
实现说明
- 采用
Column组件实现垂直列布局,按日期、标题、内容的顺序从上到下排列三个文本字段 - 不同字段配置了差异化字体样式、组件间加了固定间距,视觉层级清晰,不会出现内容挤在一起的问题
- 提供两种列表渲染方案:列表数据量小的时候直接用
map遍历生成children写法更简洁;列表数据量大、长度不确定时用ListView.separated,系统会自动回收不可见的列表项,滚动性能更好 - 所有数据项都包裹在Card组件内,符合数据块的展示样式要求
内容的提问来源于stack exchange,提问作者Reni Setyaningsih
相关产品推荐
相关产品推荐

