Flutter 当点击网页上的后退按钮时,Riverpod会出现错误状态异常

Flutter 当点击网页上的后退按钮时,Riverpod会出现错误状态异常,flutter,riverpod,Flutter,Riverpod,当有人点击他们网页上的后退按钮时,我在StateNotifiers中发现了这个错误。我已经将它隔离到下面的longRunningAPI请求发生的地方 Exception has occurred. "Error: Bad state: Tried to use RunListNotifier after `dispose` was called. 我有这样的代码 final runListController = StateNotifierProvider.autoDispose

当有人点击他们网页上的后退按钮时,我在StateNotifiers中发现了这个错误。我已经将它隔离到下面的
longRunningAPI
请求发生的地方

Exception has occurred.
"Error: Bad state: Tried to use RunListNotifier after `dispose` was called.
我有这样的代码

final runListController = StateNotifierProvider.autoDispose
    .family<RunListNotifier, AsyncValue<List<Run>>, RunListParameter>(
        (ref, param) {
  return RunListNotifier(read: ref.read, param: param);
});

class RunListNotifier extends StateNotifier<AsyncValue<List<Run>>> {
  RunListNotifier({required this.read, required this.param})
      : super(AsyncLoading()) {
    fetchViaAPI(param);
  }

  final Reader read;
  final RunListParameter param;
  void fetchViaAPI(RunListParameter param) async {
    state = AsyncLoading();
    try {
      List<Run> stuff = await read(apiProvider).longRunningAPI(param: param);
      state = AsyncData(stuff);
    } catch (e) {
      state = AsyncError(e);
    }
  }
}

我相信您可以通过在设置API调用后的状态之前检查
mounted
来解决此问题,如下所示:

List stuff=wait read(apiProvider).longRunningAPI(param:param);
如果(!已安装)返回;
state=异步数据(stuff);
这只是检查是否调用了dispose,如果是,则不要尝试修改状态

另一个有用的资源是在API调用中添加
cancelToken
,并在释放提供程序时取消

final longRunningApi=FutureProvider.autoDispose.family((ref,param)异步{
final cancelToken=cancelToken();
参考onDispose(cancelToken.cancel);
最终api=等待参考手表(apiProvider);
final res=等待api.longRunningApi(参数、取消令牌);
ref.maintaintState=true;
返回res;
});

然后,您必须将cancelToken添加到实际请求中。在《Riverpod》作者的文章中可以找到一个很好的例子。

这非常有用。谢谢你,亚历克斯。
    } catch (e) {
      if (e.runtimeType.toString() == 'StateError') {
         // ignore the error
      } else {
         state = AsyncError(e);
      }
    }