flutter 如何在释放小部件时更新StateProvider?

wtlkbnrh  于 2023-02-20  发布在  Flutter
关注(0)|答案(1)|浏览(155)

如果我尝试通过重写小部件dispose方法来更新stateProvider,我会得到一个异常,如下所示。知道如何更新状态,以便下次重建此小部件时使用null状态吗?
代码:

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

错误:

════════ 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.
ohfgkhjo

ohfgkhjo1#

释放小部件时如何使用addPostFrameCallback更新StateProvider的示例

@override
void dispose() {
  WidgetsBinding.instance.addPostFrameCallback((_) {
    ref.read(fsdMapStateProvider.notifier).state = null;
  });
  super.dispose();
}

我们正在调度一个回调函数,在当前帧绘制完成后将fsdMapStateProvider的状态设置为null,这样可以确保在状态更新时,小部件树仍然保持稳定。

相关问题