Riverpod FutureProvider 提供不可能的 AsyncValue 依赖注入

问题描述

我有一个由 LectureRepository 实现的抽象类 LectureRepositoryImplLectureRepositoryImpl

初始化 SharedPreferences sharedPreferences
LectureLocalDataSourceImpl({@required this.sharedPreferences})

现在我想使用 Riverpod 访问存储库,所以我这样做:

    FutureProvider<LectureLocalDataSource>(
  (ref) async {
    return LectureLocalDataSourceImpl(sharedPreferences: await SharedPreferences.getInstance());
  },);

但现在在 lectureRepositoryProvider 中,我读取了 lectureLocalDataRepositoryProvider 我在值 localDataSource 中获得了一个 AsyncValue,我无法在此处分配:

final lectureRepositoryProvider = FutureProvider<LectureRepository>((ref) async {
  final localDataSource = ref.read(lectureLocalDataRepositoryProvider);
  return LectureRepositoryImpl(localDataSource: localDataSource);
});

我应该如何处理 AsyncValue?

解决方法

如果像这样工作,我就用 SharedPreferences 持久化了主题:

final sharedPreferences =
    FutureProvider((ref) => SharedPreferences.getInstance());

final themeChangeNotifier = ChangeNotifierProvider<ThemeChangeNotifier>((ref) {
  final prefs = ref.watch(sharedPreferences)?.data?.value;
  return ThemeChangeNotifier(prefs);
});

并像这样使用它:

 final isDartTheme = watch(themeChangeNotifier).isDarkTheme;
    final prefs = watch(sharedPreferences);
    return prefs.when(
      loading: () => Material(
        child: CircularProgressIndicator(),),data: (_) => MaterialApp(
        title: 'Flutter Demo',theme: isDartTheme ? ThemeData.dark() : ThemeData.light(),home: SearchPage(),error: (_,__) => SizedBox.shrink(),);

我希望能在几天内发布视频和 repo :)

,

您可以在 AsyncValue 上调用 .data,它为您提供基础数据值。如果您需要区分加载、数据和错误,AsyncValue 文档将解释如何。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...