使用TextFieldTags组件出现FocusNode已释放后仍被使用的错误
这个错误的核心原因是页面销毁时,TextFieldTagsController内部关联的FocusNode已被释放,但再次进入页面时复用了已销毁的控制器实例,导致尝试使用已释放的FocusNode。针对textfield_tags ^1.4.4版本,按以下步骤修复:
1. 正确管理控制器的生命周期
- 在页面State类中延迟声明控制器,避免提前初始化:
late TextFieldTagsController _tagController; - 在
initState方法中初始化控制器,确保每次进入页面都创建新实例:@override void initState() { super.initState(); _tagController = TextFieldTagsController(); // 如需恢复之前的标签,在这里给tags列表赋值 // tags = [...previousTags]; } - 在
dispose方法中销毁控制器,释放内部资源:@override void dispose() { _tagController.dispose(); super.dispose(); }
2. 确保标签列表状态正确
如果需要保留之前输入的标签,不要依赖控制器缓存,而是在页面初始化时手动恢复tags列表状态(比如从父页面传递、本地存储读取等),避免控制器复用旧的已释放资源。
修改后的完整State类示例
class YourPageState extends State<YourPage> { late TextFieldTagsController _tagController; List<String> tags = []; @override void initState() { super.initState(); _tagController = TextFieldTagsController(); // 可添加标签恢复逻辑,比如从参数获取 // if (widget.initialTags != null) { // tags = List.from(widget.initialTags!); // } } @override void dispose() { _tagController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( body: TextFieldTags( textFieldTagsController: _tagController, textSeparators: const [" ", ','], initialTags: tags, // 恢复初始标签 onTag: (tag) { tags.add(tag); }, onDelete: (tag) { tags.remove(tag); }, validator: (tag) { if (tag.length < 3) { return "标签长度不能少于3个字符。"; } return null; }, tagsStyler: TagsStyler( tagTextStyle: const TextStyle( fontFamily: 'Chivo', fontWeight: FontWeight.normal), tagDecoration: BoxDecoration( color: const Color(0xFFDBE2E7), borderRadius: BorderRadius.circular(0.0), ), tagCancelIcon: Icon(Icons.cancel, size: 18.0, color: Colors.blue[900]), tagPadding: const EdgeInsets.all(6.0), ), textFieldStyler: TextFieldStyler( hintText: "输入相关关键词", textFieldBorder: const OutlineInputBorder( borderSide: BorderSide(color: Color(0xFFDBE2E7), width: 2), ), ), ), ); } }
内容的提问来源于stack exchange,提问作者Krishnaa Krishna
相关产品推荐
相关产品推荐

