Flutter自定义Widget的GestureDetector:跨页面删除列表元素
实现自定义标签Widget的删除功能
要让tagRetrievePreview的删除按钮能移除父页面列表中的对应元素,只需通过回调函数将删除逻辑从父页面传递给子Widget即可,具体步骤如下:
1. 修改自定义Widget,添加删除回调
更新tagRetrievePreview类,新增一个onDelete回调参数,用于接收父页面的删除逻辑:
import 'package:flutter/material.dart'; // 遵循Dart命名规范,类名改为大驼峰 class TagRetrievePreview extends StatelessWidget { final String tag; // 用final修饰不可变成员变量 final VoidCallback onDelete; // 删除回调函数 // 构造函数参数改为命名参数,明确传递意图 const TagRetrievePreview({ required this.tag, required this.onDelete, Key? key, }) : super(key: key); @override Widget build(BuildContext context) { return Row( mainAxisSize: MainAxisSize.min, children: [ Card( color: const Color.fromARGB(255, 224, 223, 223), shape: RoundedRectangleBorder( side: const BorderSide( color: Color.fromARGB(255, 83, 83, 83), ), borderRadius: BorderRadius.circular(50), ), child: Padding( padding: const EdgeInsets.all(3.0), child: Row( children: [ Text( tag, style: TextStyle(color: Colors.grey.shade800), textAlign: TextAlign.center, ), Padding( padding: const EdgeInsets.all(2.0), child: GestureDetector( // 点击时触发父页面传入的删除回调 onTap: onDelete, child: const CircleAvatar( radius: 8, backgroundColor: Color.fromARGB(255, 117, 112, 112), child: Icon( Icons.close, size: 13, color: Color.fromARGB(255, 255, 255, 255), )), ), ), ], ), ), ), ], ); } }
2. 在父页面中传递删除逻辑
假设父页面是StatefulWidget,tags是存储标签的List<String>,在ListView.builder中给每个TagRetrievePreview传入删除当前标签的逻辑:
Flexible( fit: FlexFit.loose, child: ListView.builder( shrinkWrap: true, itemCount: tags.length, itemBuilder: (_, index) { final currentTag = tags[index]; return Padding( padding: const EdgeInsets.symmetric(horizontal: 5.0, vertical: 3.0), child: TagRetrievePreview( tag: currentTag, onDelete: () { // 通过setState更新列表,触发页面刷新 setState(() { tags.removeAt(index); }); }, ), ); }, ), ),
核心逻辑说明
- 子Widget通过回调函数将点击事件传递给父组件,由父组件负责修改数据源(
tags列表) - 调用
setState会触发页面重新构建,ListView会自动更新显示的标签列表 - 遵循Dart的代码规范,优化了类名、成员变量的定义,提升代码可读性
内容的提问来源于stack exchange,提问作者Tindona
相关产品推荐
相关产品推荐

