如何在销毁小部件时更新 StateProvider?

huangapple go评论53阅读模式
英文:

How to update a StateProvider when disposing a widget?

问题

Code:

@override
void dispose() {
  // 重置任何请求映射的初始状态
  ref.read(fsdMapStateProvider.notifier).state = null;
  super.dispose();
}

Error:

════════════════════════════════════ 错误信息 ════════════════════════════════════
在构建小部件树完成时,抛出了以下断言:
查找已停用小部件的祖先是不安全的。

此时,小部件元素树的状态不再稳定。

为了安全地在dispose()方法中引用小部件的祖先,请在小部件的didChangeDependencies()方法中调用dependOnInheritedWidgetOfExactType()来保存对祖先的引用。
英文:

If I try and update the stateProvider by overriding the widgets dispose method I get an exception as shown below. Any idea how to update the state, so that the next time this widget is rebuilt it's using the state of null:

Code:

@override
void dispose() {
  //reset any request map initial bounds
  ref.read(fsdMapStateProvider.notifier).state = null;
  super.dispose();
}

Error:

════════ Exception caught by widgets library ═══════════════════════════════════
The following assertion was thrown while finalizing the widget tree:
Looking up a deactivated widget's ancestor is unsafe.

At this point the state of the widget's element tree is no longer stable.

To safely refer to a widget's ancestor in its dispose() method, save a reference to the ancestor by calling dependOnInheritedWidgetOfExactType() in the widget's didChangeDependencies() method.

答案1

得分: 2

尝试使用deactivate方法而不是dispose

此方法在小部件从小部件树中移除之前调用,也就是在小部件完全被处理之前调用。

@override
void deactivate() {
  // 重置任何请求映射的初始边界
  ref.read(fsdMapStateProvider.notifier).state = null;
  super.deactivate();
}

文档链接:deactivate方法

英文:

Try the deactivate method rather than the dispose.

This method gets called before the widget is removed from the widget tree, meaning just before the widget gets fully disposed.

@override
void deactivate() {
  //reset any request map initial bounds
  ref.read(fsdMapStateProvider.notifier).state = null;
  super.deactivate();
}

Docs: deactivate method

huangapple
  • 本文由 发表于 2023年2月19日 07:52:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/75497148.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定