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
相关产品推荐
相关产品推荐

