[英]How do I get loading state/spinner with flutter riverpod statenotifier, ref watch and asyncvalue?
[英]Flutter - RiverPod Newbie. How to watch StateNotifier in my view
我有一个从 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());
这里我有一个 Class 我想用它来控制 UI 的 state
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 包装在一个读取文件中。
在我的用户界面中,我想查看食谱列表
return Consumer(
builder: (context, watch, child) {
return watch(recipeAsyncController).when();
},
);
尝试访问 when 异步调用时。
https://pub.dev/documentation/flutter_riverpod/latest/flutter_riverpod/Consumer-class.html
builder function 中的第二个参数实际上是一个参考 object。
return Consumer(
builder: (context, ref, child) {
return ref.watch(recipeAsyncController).when();
},
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.