问题描述
我是 Riverpod 的新手,虽然这些文章对入门很有帮助,但我正在努力应对陈旧状态。
当用户登录时,我正在设置一些状态。当 DB 中状态的详细信息发生变化时,我希望重建自动发生。虽然我能够从数据库获取流,但我无法将数据库更改连接到 riverpod 状态。
该模式用于协作。两个用户在独立的手机、平板电脑等上处理应用程序的同一部分。
我正在使用来自 firecloudstore 的文档流和集合流。
任何有用的文章或您如何使用riverpod解决这个问题?我是否必须为此投入时间学习 BLoC 之类的东西?
解决方法
你绝对不需要学习 BLoC 来完成你想要的。
您说您使用的是 firebase 流,因此这里有一个在您的数据发生变化时实时重建的示例。
首先,您的存储库层。
class YourRepository {
YourRepository(this._read);
static final provider = Provider((ref) => YourRepository(ref.read));
final Reader _read;
Stream<YourModel?> streamById(String id) {
final stream = FirebaseFirestore.instance.collection('YourCollection').doc(id).snapshots();
return stream.map((event) => event.exists ? YourModel.fromJson(event.data()!) : null);
}
}
接下来,定义一个 StreamProvider 来读取存储库中定义的流。
final streamYourModelById = StreamProvider.autoDispose.family<YourModel?,String>((ref,id) {
return ref.watch(YourRepository.provider).streamById(id);
});
最后,在小部件中使用 StreamProvider 以在数据更改时重新加载。
// Hooks
class YourWidget extends HookWidget {
const YourWidget({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
body: useProvider(streamYourModelById('YourDataId')).when(
loading: () => const Center(child: CircularProgressIndicator()),error: (err,stack) => Center(child: Text(err.toString())),data: (yourData) => Center(child: Text(yourData?.toString() ?? 'Got Null')),),);
}
}
// Without Hooks
class YourWidget extends ConsumerWidget {
const YourWidget({Key? key}) : super(key: key);
@override
Widget build(BuildContext context,ScopedReader watch) {
return Scaffold(
body: watch(streamYourModelById('YourDataId')).when(
loading: () => const Center(child: CircularProgressIndicator()),);
}
}
您应该能够应用此模式来完成您需要的任何事情。