Flutter使用InheritedWidget时子组件未随父组件重建问题
Flutter InheritedWidget状态不更新问题修复
问题
使用InheritedWidget搭建状态管理系统时,点击底部加减按钮修改myCoupons集合后,MyCouponsColumn中的优惠券列表未自动刷新,仅热重载后才生效。
问题原因
AppStateScope的updateShouldNotify方法判断逻辑错误:
@override bool updateShouldNotify(AppStateScope oldWidget) { return data == oldWidget.data; }
自定义类AppState的==默认比较对象引用,每次调用copyWith都会生成新的AppState实例,导致data == oldWidget.data始终返回false,InheritedWidget不会通知依赖组件重建。
修复方法
修改updateShouldNotify方法,改为比较myCoupons集合的内容是否变化:
方法1:使用setEquals(需导入package:flutter/foundation.dart)
import 'package:flutter/foundation.dart'; // 导入此包使用setEquals class AppStateScope extends InheritedWidget { // ... 其他代码不变 @override bool updateShouldNotify(AppStateScope oldWidget) { return !setEquals(data.myCoupons, oldWidget.data.myCoupons); } }
方法2:手动实现集合比较
如果不想导入额外包,可手动遍历比较:
@override bool updateShouldNotify(AppStateScope oldWidget) { // 先比较长度,长度不同直接返回true if (data.myCoupons.length != oldWidget.data.myCoupons.length) return true; // 遍历检查每个元素是否存在于旧集合中 for (final coupon in data.myCoupons) { if (!oldWidget.data.myCoupons.contains(coupon)) { return true; } } return false; }
验证
修复后点击加减按钮,MyCouponsColumn会自动根据myCoupons集合的变化重建列表,无需手动热重载。
内容的提问来源于stack exchange,提问作者Felix Kniest
相关产品推荐
相关产品推荐

