Riverpod FutureProvider 无法提供 AsyncValue 依赖注入

问题描述 投票:0回答:2

我有一个由

LectureRepository
实现的抽象类
LectureRepositoryImpl
LectureRepositoryImpl
 初始化 
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
2个回答
1
投票

我做了这样的工作,为了一个与

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(),
    );

我希望几天后发布视频和存储库:)


1
投票

您可以在 AsyncValue 上调用

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

编辑:对于 Riverpod 2,正确的调用是

.requireData
,它将为您提供数据,或者如果处于错误或加载状态,则会 抛出

© www.soinside.com 2019 - 2024. All rights reserved.