用途:Riverpod 在 provider 计算抛出异常时会自动重试,本技能介绍如何定制这一行为,包括重试函数、按 provider 与全局设置、禁用重试、ProviderException 处理以及等待重试完成。
默认行为:provider 默认最多重试一定次数(例如 10 次),采用指数退避(例如 200ms 到 6.4s)。Error 与 ProviderException 不会重试:Error 表示代码缺陷;ProviderException 表示某个依赖失败,因此依赖它的 provider 不重试,而是重试底层那个 provider。
自定义重试函数:签名为 Duration? Function(int retryCount, Object error)。返回 Duration 表示下次重试前的延迟,返回 null 表示停止重试。示例: Duration? myRetry(int retryCount, Object error) { if (retryCount >= 5) return null; if (error is ProviderException) return null; return Duration(milliseconds: 200 * (1 << retryCount)); }
设置位置:按 provider 设置,在定义 provider 时传入 retry: myRetry(使用代码生成时为 @Riverpod(retry: myRetry));全局设置,将 retry: myRetry 传给 ProviderScope 或 ProviderContainer。示例: ProviderScope(retry: myRetry, child: MyApp()) final myProvider = Provider<int>(retry: myRetry, (ref) => 0);
禁用重试:始终返回 null,例如 ProviderScope(retry: (retryCount, error) => null, child: MyApp())。
等待带重试的异步 provider:ref.watch(myProvider.future) 会持续等待,直到所有重试耗尽或 provider 成功。因此 await ref.watch(myProvider.future) 会跳过中间失败,在 provider 最终成功或放弃时完成。
限制:资料未提供具体版本要求、平台限制或性能影响说明。