Flutter中如何配置Provider的Consumer仅监听类特定方法触发重建
实现方案
默认Consumer会监听ChangeNotifier发出的所有notifyListeners通知,没有过滤规则,只要通知发送就会触发重建。要实现仅监听特定方法的触发,推荐以下两种成熟方案:
方案1:使用Selector组件(官方推荐)
这是Provider生态原生支持的实现方式,核心是通过selector筛选你关心的状态,只有筛选值变化时才触发重建。
第一步:修改ChangeNotifier类,新增方法触发标识
class Example with ChangeNotifier{ // 用于标记exampleOneMethod是否被调用,用bool翻转或者int计数都可以 bool _exampleOneTriggered = false; bool get exampleOneTriggered => _exampleOneTriggered; void exampleMethod(){ //....执行业务逻辑 notifyListeners(); } void exampleOneMethod(){ //....执行业务逻辑 // 调用时更新标识 _exampleOneTriggered = !_exampleOneTriggered; notifyListeners(); } }
第二步:组件层用Selector代替Consumer
// 泛型第二个参数是你筛选出来的标识类型 Selector<Example, bool>( // selector函数返回你关心的筛选值 selector: (context, exampleInstance) => exampleInstance.exampleOneTriggered, // 只有selector返回的值发生变化时,builder才会执行 builder: (context, exampleInstance, child) => SomeWidget(), )
方案2:用ValueNotifier单独管理事件通知
如果不想污染原ChangeNotifier的状态,也可以单独为需要监听的方法绑定独立的可监听对象,从根源上避免收到其他方法的通知:
第一步:修改ChangeNotifier类
class Example with ChangeNotifier{ // 单独创建ValueNotifier对应exampleOneMethod的触发事件 final exampleOneEvent = ValueNotifier<bool>(false); void exampleMethod(){ //....执行业务逻辑 notifyListeners(); } void exampleOneMethod(){ //....执行业务逻辑 // 仅更新对应ValueNotifier的值 exampleOneEvent.value = !exampleOneEvent.value; notifyListeners(); } }
第二步:组件层直接监听对应ValueNotifier
ValueListenableBuilder( valueListenable: Provider.of<Example>(context, listen: false).exampleOneEvent, builder: (context, value, child) => SomeWidget(), )
注意事项
- 如果selector返回的是自定义类对象,需要手动覆写该类的
==运算符和hashCode,否则Selector无法正确判断值是否发生变化 - 标识位用bool翻转、int自增都可以,只要每次方法调用时标识值发生变化即可
内容的提问来源于stack exchange,提问作者Zilaid
相关产品推荐
相关产品推荐

