【发布时间】: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 异步调用时。
【问题讨论】: