如果用户文档在 Firestore 上发生更改,请更新提供程序中的用户数据



如果用户文档在 firestore 上发生更改,我想更新提供程序中的用户数据。

实际上,我使用提供程序将当前用户数据存储在名为 _currentUser 的变量中。此变量有助于在多个屏幕上显示用户数据。

class UserService extends ChangeNotifier {
final CollectionReference usersCollection =
FirebaseFirestore.instance.collection('users');
late User _currentUser;
User get currentUser => _currentUser;
Future<User> getUser(String uid) async {
var userData = await usersCollection.doc(uid).get();
User user = User.fromMap(userData.data()!);
_currentUser = user;
print("nb lives : ${_currentUser.nbLives}");
notifyListeners();
return user;
}
}

当前用户数据可能会随着时间的推移而变化,我当前解决方案的问题是,如果用户文档已更改,则_currentUser变量不会更新,旧数据显示在应用程序屏幕上。我想找到一种方法来收听此文档并在用户数据发生更改时更新_currentUser变量。

我找到的解决方案是使用 Streams 获取用户数据,但我不喜欢它,因为它在特定屏幕上运行而不是在后台运行。

有没有人遇到过类似的问题?感谢您的帮助!

class UserService extends ChangeNotifier {
final CollectionReference usersCollection =
FirebaseFirestore.instance.collection('users');
late User _currentUser;
User get currentUser => _currentUser;
void init(String uid) async {
// call init after login or on splash page (only once) and the value
// of _currentUser should always be updated.
// whenever you need _currentUser, just call the getter currentUser.
usersCollection.doc(uid).snapshots().listen((event) {
_currentUser = User.fromMap(event.data()!);
notifyListeners();
});
}
}

您可以通过多种方式执行此操作

  1. 当您在 firestore 中更新_currentUser时,请使用notifylistner更新提供程序变量中的相同内容,并在 Consumer 中包装使用该_currentUser的小部件,以便更改始终更新。

  2. 在您的根小部件中使用带有流的流构建器:....快照() 并在更改时更新_currentUser

这取决于您的用例,并希望事情对_currentUser的变化做出反应。

最新更新