Flutter中如何使用ListView.builder展示newvoucherlist列表?
相关参考界面:
实现步骤
- 定义优惠券数据模型
统一数据结构避免字段混乱,示例如下:
class VoucherModel { final String id; final double discountAmount; // 优惠金额 final String useCondition; // 使用门槛,如满100可用 final String title; // 优惠券名称 final DateTime expireDate; // 有效期 final int status; // 0可领取 1已领取 2已过期 VoucherModel({ required this.id, required this.discountAmount, required this.useCondition, required this.title, required this.expireDate, required this.status, }); }
- 初始化
newvoucherlist数据源
可直接将接口返回的字段映射到上述模型,生成对应列表,模拟数据示例如下:
List<VoucherModel> newvoucherlist = [ VoucherModel( id: "001", discountAmount: 20, useCondition: "满100元可用", title: "全品类通用优惠券", expireDate: DateTime(2024, 12, 31), status: 0, ), VoucherModel( id: "002", discountAmount: 50, useCondition: "满300元可用", title: "家电专属优惠券", expireDate: DateTime(2024, 10, 30), status: 1, ), ];
- 嵌套
ListView.builder实现懒加载列表
直接绑定数据源,渲染对应优惠券卡片即可,基础实现代码如下:
ListView.builder( padding: const EdgeInsets.all(12), // 列表长度和数据源长度保持同步 itemCount: newvoucherlist.length, // 如果列表嵌套在其他可滚动父组件内,可添加下面两个属性避免滚动冲突 shrinkWrap: true, physics: const NeverScrollableScrollPhysics(), itemBuilder: (context, index) { // 取当前索引对应的优惠券数据 VoucherModel currentVoucher = newvoucherlist[index]; // 可根据参考界面自行调整卡片样式 return Card( margin: const EdgeInsets.only(bottom: 12), child: Padding( padding: const EdgeInsets.all(16), child: Row( children: [ // 左侧优惠金额区域 Text( "¥${currentVoucher.discountAmount.toStringAsFixed(0)}", style: const TextStyle( color: Colors.red, fontSize: 24, fontWeight: FontWeight.bold, ), ), const SizedBox(width: 16), // 中间优惠券信息区域 Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( currentVoucher.title, style: const TextStyle( fontSize: 16, fontWeight: FontWeight.w500, ), ), const SizedBox(height: 4), Text(currentVoucher.useCondition), const SizedBox(height: 4), Text( "有效期至:${currentVoucher.expireDate.year}-${currentVoucher.expireDate.month}-${currentVoucher.expireDate.day}", style: const TextStyle(color: Colors.grey, fontSize: 12), ), ], ), ), const SizedBox(width: 12), // 右侧操作按钮 ElevatedButton( onPressed: currentVoucher.status == 0 ? () { // 处理优惠券领取逻辑 } : null, child: Text(currentVoucher.status == 0 ? "立即领取" : currentVoucher.status == 1 ? "已领取" : "已过期"), ), ], ), ), ); }, )
注意事项
- 如果列表需要单独滚动,删除
shrinkWrap和physics两个属性即可 - 卡片样式、展示字段可根据参考界面自行调整,
ListView.builder仅负责绑定数据源和懒加载渲染,无需修改核心逻辑 - 接口返回数据后直接更新
newvoucherlist再触发页面刷新,即可完成列表内容更新
内容的提问来源于stack exchange,提问作者Farzana Rumpa
相关产品推荐
相关产品推荐

