我编写了一个 StreamProvider,我在启动后立即收听,以获取有关潜在登录用户的所有信息。如果没有用户,那么结果将为空,监听器保持在加载状态,所以我决定发回一个空用户的默认值,让我知道加载完成。我必须这样做,因为 Hive 的 watch() 方法仅在数据更改时触发,而在启动时不会触发。所以在那之后,我希望 watch() 方法完成它的工作,但问题在于以下场景:
启动时:无用户 -插入用户 -> watch 方法被触发 -> 我得到插入的用户数据 -> 删除登录的用户 -> watch 方法没有被触发。
启动时:完整用户-删除用户->触发监视方法->我得到一个空用户->插入用户->未触发监视方法。
一段时间后,我发现我可以随心所欲地使用所有 CRUD 操作,并且 Hive 的盒子做了它应该做的事情,但是 watch() 方法在它被触发一次后不再被触发。
流提供者:
final localUsersBoxFutureProvider = FutureProvider<Box>((ref) async {
final usersBox = await Hive.openBox('users');
return usersBox;
});
final localUserStreamProvider = StreamProvider<User>((ref) async* {
final usersBox = await ref.watch(localUsersBoxFutureProvider.future);
yield* Stream.value(usersBox.get(0, defaultValue: User()));
yield* usersBox.watch(key: 0).map((usersBoxEvent) {
return usersBoxEvent.value == null ? User() : usersBoxEvent.value as User;
});
});
聆听者:
return localUserStream.when(
data: (data) {
if (data.name == null) {
print('Emitted data is an empty user');
} else {
print('Emitted data is a full user');
}
return Container(color: Colors.blue, child: Center(child: Row(children: [
RawMaterialButton(
onPressed: () async {
final globalResponse = await globalDatabaseService.signup({
'email' : 'name@email.com',
'password' : 'password',
'name' : 'My Name'
});
Map<String, dynamic> jsonString = jsonDecode(globalResponse.bodyString);
await localDatabaseService.insertUser(User.fromJSON(jsonString));
},
child: Text('Insert'),
),
RawMaterialButton(
onPressed: () async {
await localDatabaseService.removeUser();
},
child: Text('Delete'),
)
])));
},
loading: () {
return Container(color: Colors.yellow);
},
error: (e, s) {
return Container(color: Colors.red);
}
);
CRUD 方法:
Future<void> insertUser(User user) async {
Box usersBox = await Hive.openBox('users');
await usersBox.put(0, user);
await usersBox.close();
}
Future<User> readUser() async {
Box usersBox = await Hive.openBox('users');
User user = usersBox.get(0) as User;
await usersBox.close();
return user;
}
Future<void> removeUser() async {
Box usersBox = await Hive.openBox('users');
await usersBox.delete(0);
await usersBox.close();
}
知道如何告诉 StreamProvider watch() 方法应该保持活动状态,即使一个值已经发出?