Riverpod - 以更好/优雅的方式创建具有异步依赖项的服务

aid*_*ack 6 flutter riverpod

我编写了一些提供 aApiService到 a 的代码StateNotifier。依赖ApiServiceauthenticatorclient- 身份验证客户端必须异步创建,因为它使用共享首选项来获取令牌。

我只是想弄清楚他们是否是我写这篇文章的更优雅的方式。基本上,当服务 apiService 被注入到 StateNotifier 中时,它可能可以为空......对我来说,这有点代码味道。

简而言之,这就是我正在做的事情...使用 aFutureProvider来实例化RestClientaDio

authenticatorClient = FutureProvider<RestClient>((ref) async {
  final prefs = await SharedPreferences.getInstance();
  final dio = Dio();
  ...
  return RestClient(dio);
}
Run Code Online (Sandbox Code Playgroud)

然后我观看并使用 MaybeWhen 返回服务

final clientCreatorWatchProvider = Provider<ApiService?>((ref) => ref
    .watch(authenticatorClient)
    .whenData((value) => ApiService(value))
    .maybeWhen(
      data: (service) => service,
      orElse: () => null,
    ));
Run Code Online (Sandbox Code Playgroud)

所以我不喜欢的是 orElse 返回 null

然后我的StateNotifier就在看...

final AppState = StateNotifierProvider<AppNotifier, String>(
    (ref) => AppNotifier(ref.watch(clientCreatorWatchProvider)));

class AppNotifier extends StateNotifier<String> {
  final ApiService? apiService;

  AppNotifier(this.apiService) : super("loading") {
    init();
  }
...
}

Run Code Online (Sandbox Code Playgroud)

对上述方法有什么想法吗?

谢谢

Ale*_*ord 20

解决此问题的一种方法是在SharedPreferences提供程序外部进行初始化。然后,您可以用来ProviderScope覆盖同步提供程序,从而无需使用AsyncValue.

初始化应用程序时,请执行以下操作:

final sharedPreferences = Provider<SharedPreferences>((_) => throw UnimplementedError());

Future<void> main() async {
  final sharedPrefs = await SharedPreferences.getInstance();

  runApp(
    ProviderScope(
      overrides: [
        sharedPreferences.overrideWithValue(sharedPrefs),
      ],
      child: MyApp(),
    ),
  );
}
Run Code Online (Sandbox Code Playgroud)

现在你可以像这样编写你的提供者:

final authenticatorClient = Provider<RestClient>((ref) {
  final prefs = ref.watch(sharedPreferences);
  final dio = Dio();
  ...
  return RestClient(dio);
}

final clientCreatorWatchProvider = Provider<ApiService>((ref) {
  final authClient = ref.watch(authenticatorClient);
  return ApiService(authClient);
});
Run Code Online (Sandbox Code Playgroud)