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

Flutter中如何用ListView.Builder仅渲染MyList中bool为true的MyItem

Flutter 过滤列表并使用 ListView.Builder 渲染指定项

你可以先对原列表 MyList 做过滤,只保留 bool 属性为 true 的 MyItem 实例,再基于过滤后的列表构建 ListView.Builder,具体实现如下:

1. 定义自定义类 MyItem

class MyItem {
  final String text;
  final bool isActive;

  MyItem({required this.text, required this.isActive});
}

2. 过滤列表并构建 ListView.Builder

// 假设你的原始列表示例
List<MyItem> myList = [
  MyItem(text: "第一项", isActive: true),
  MyItem(text: "第二项", isActive: false),
  MyItem(text: "第三项", isActive: true),
];

// 过滤出bool属性为true的项
List<MyItem> filteredList = myList.where((item) => item.isActive).toList();

// 渲染过滤后的列表
ListView.builder(
  itemCount: filteredList.length,
  itemBuilder: (context, index) {
    MyItem currentItem = filteredList[index];
    return ListTile(
      title: Text(currentItem.text),
    );
  },
)

说明

  • 用 where((item) => item.isActive) 筛选符合条件的项,再通过 toList() 转换成可用于构建列表的新集合
  • ListView.Builder 的 itemCount 直接使用过滤后列表的长度,确保只渲染符合要求的项
  • 在 itemBuilder 中直接从过滤后的列表取对应索引的项,即可构建对应的列表UI

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 21:25:53