【问题标题】:Flutter - RiverPod Newbie. How to watch StateNotifier in my viewFlutter - RiverPod 新手.在我看来如何观看 StateNotifier
【发布时间】:2021-12-20 01:07:06
【问题描述】:

我有一个从 FireStore 获取食谱的食谱库

class RecipeRepository {

  Future<List<Recipe>> readAll() async {
    final snap = await _recipeRef.get();
    return snap.docs.map((doc) => doc.data()).toList();
  }
}

这里我将存储库作为提供者返回

final recipeRepositoryProvider =
    Provider<RecipeRepository>((ref) => RecipeRepository());

这里我有一个类,我想用它来控制 UI 的状态

final recipeAsyncController =
    StateNotifierProvider<RecipeAsyncNotifier, AsyncValue<List<Recipe>>>(
        (ref) => RecipeAsyncNotifier(ref.read));

class RecipeAsyncNotifier extends StateNotifier<AsyncValue<List<Recipe>>> {
  RecipeAsyncNotifier(this._read) : super(const AsyncLoading()) {
    init();
  }
  final Reader _read;

  init() async {
    final recipes = await _read(recipeRepositoryProvider).readAll();
    state = AsyncData(recipes);
  }
}

如您所见,我将 recipeRepositoryProvider 包装在读取中。

在我的 UI 我想查看食谱列表

    return Consumer(
      builder: (context, watch, child) {
        return watch(recipeAsyncController).when();
      },
    );

问题是我收到以下错误。

尝试访问 when 异步调用时。

【问题讨论】:

    标签: flutter riverpod


    【解决方案1】:

    https://pub.dev/documentation/flutter_riverpod/latest/flutter_riverpod/Consumer-class.html

    builder 函数中的第二个参数实际上是一个 ref 对象。

      return Consumer(
          builder: (context, ref, child) {
            return ref.watch(recipeAsyncController).when();
          },
        );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-04
      • 1970-01-01
      • 2021-05-24
      • 2021-03-17
      • 1970-01-01
      • 2021-04-21
      • 2021-03-26
      • 2021-12-01
      相关资源
      最近更新 更多