Flutter 如何实现点击图标删除 ListView.builder 渲染的列表项
实现步骤
1. 定义本地可变存储列表
你当前直接使用Future返回的snapshot.data渲染页面,这份数据是不可变的,修改后无法触发UI刷新,所以先在当前页面的State类中新增可变列表变量:
class YourPageState extends State<YourPage> { // 存储历史记录的本地可变列表 List<History> localHistoryList = []; // 原有其他代码保持不变 }
2. 接口数据赋值到本地列表
修改FutureBuilder的逻辑,首次拿到接口返回数据时赋值给本地列表,后续渲染全部使用本地可变列表:
Container( // 删掉冗余的外层SingleChildScrollView,避免和ListView.builder滚动冲突 child: FutureBuilder( future: _getRecord(), builder: (BuildContext context, AsyncSnapshot<List<History>> snapshot) { if (snapshot.hasData) { // 首次拿到接口数据时赋值给本地列表 if(localHistoryList.isEmpty) { localHistoryList = List.from(snapshot.data!); } if(localHistoryList.isNotEmpty){ return Container( padding: EdgeInsets.zero, child: ListView.builder( // 用本地列表长度控制渲染数量 itemCount: localHistoryList.length, itemBuilder: (BuildContext context, int index) { final currentRecord = localHistoryList[index]; return ListTile( leading: CircleAvatar( radius: 25, backgroundColor: Color(int.parse(annualboxcolor)), child: Container( padding: EdgeInsets.fromLTRB(0, 10, 0, 0), child: Column( children: [ Text(dateObj.day.toString()), ] ), ) ), title: Text(currentRecord.username), isThreeLine: true, subtitle: IconButton( icon: Icon(Icons.check_box, color: Colors.green, size: 30,), onPressed: () { // 核心删除逻辑 setState(() { localHistoryList.removeAt(index); }); // 如果需要同步删除后端数据,可在这里加对应的接口请求逻辑 // 示例:_deleteRecordFromServer(currentRecord.id); } ) ); } ) ); } // 列表为空的占位逻辑可在这里补充 return const Center(child: Text('暂无记录')); } // 加载中状态逻辑可在这里补充 return const Center(child: CircularProgressIndicator()); } ) )
补充优化说明
- 你原有代码嵌套了多层垂直滚动的
SingleChildScrollView和ListView.builder,会引发滚动冲突,建议删掉外层没用的滚动容器,直接用ListView.builder处理列表滚动即可 - 如果删除操作需要和后端同步,建议先请求后端删除接口,接口返回成功后再执行
setState更新本地列表,避免前后端数据不一致
内容的提问来源于stack exchange,提问作者TimeToCode
相关产品推荐
相关产品推荐

