Search code examples
firebaseflutterdartgoogle-cloud-firestoreprovider

Update user data in provider if user document has changed on firestore


I would like to update user data in provider if user document has changed on firestore.

Actually, I use provider to store current user data in a variable called _currentUser. This variable is helpful to display user data on several screens.

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;
  }
}

Current User data can change over time and the problem of my current solution is that if user document has changed, _currentUser variable is not updated and the old data is displayed on app screens. I want to find a way to listen to this document and update _currentUser variable if user data has changed.

A solution i found is to use Streams to fetch user data but I don't like it because it runs on a specific screen and not in background.

Does anyone have ever face a similar issue ? Thank you for your help !


Solution

  • 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();
        });
      }
    }