英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论