【问题标题】:Riverpod FutureProvider provides AsyncValue Dependency Injection not possibleRiverpod FutureProvider 无法提供 AsyncValue 依赖注入
【发布时间】:2021-04-01 16:28:04
【问题描述】:

我有一个由LectureRepositoryImpl 实现的抽象类LectureRepositoryLectureRepositoryImpl 初始化 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?

【问题讨论】:

    标签: flutter asynchronous dependency-injection provider riverpod


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      我做了这样的工作,主题与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(),
          );
      

      我希望几天后会发布视频和回购 :)

      【讨论】:

        猜你喜欢
        • 2022-08-14
        • 2021-05-30
        • 2023-01-22
        • 2021-04-23
        • 1970-01-01
        • 2018-08-21
        • 2014-11-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多