randomstudent
randomstudent

Reputation: 73

DocumentSnapshot Listener

I have a question how do i listen to real-time changes to a document snapshot based on the email of the currentUser in a initState. I knew that QuerySnapshot will need to use documents.forEach to be able to retrieve but how about DocumentSnapshot. This is my code:

@override
  void initState() async{
    FirebaseUser user = await FirebaseAuth.instance.currentUser();
    Firestore.instance.collection('user').document(user.email).snapshots()
    .listen((userinfo){
      userinfo((userI){
        _fname = userI.data['FullName'];
        _SSID = userI.data['SSID'];
        _email = userI.data['email'];
        _image = userI.data['image'];
      });
    });
    super.initState();
  }

I am able to get the user.email but not able to listen to the Firestore. I can't really find anything that is similar to this maybe it's a relatively easy problem to solve for I'm still new to Flutter and Firebase. Thank you in advance.

Upvotes: 0

Views: 169

Answers (2)

Victor Eronmosele
Victor Eronmosele

Reputation: 7686

You can move your asynchronous logic into a different function and call it in your initState like this:

 @override
  void initState() {
    super.initState();
    _getUserData();
  }

  Future<void> _getUserData() async {
    FirebaseUser user = await FirebaseAuth.instance.currentUser();
    Firestore.instance.collection('user').document(user.email).snapshots()
      .listen((userinfo) {
        setState((){
          _fname = userinfo.data['FullName'];
          _SSID = userinfo.data['SSID'];
          _email = userinfo.data['email'];
          _image = userinfo.data['image'];
        });  
    });
  }

And in the widget where you use the variables, you can easily add a null check and display an empty value or a loading indicator.

Text(_fname??'')

or

_fname == null ? Center(child: CircularProgressIndicator()) : Text(_fname)

Upvotes: 1

Tirth Patel
Tirth Patel

Reputation: 5736

It should be userI.data()['some_key'] instead of userI.data['some_key'].

https://pub.dev/documentation/cloud_firestore/latest/cloud_firestore/DocumentSnapshot/data.html

Also reomve userInfo, it should be like this:

Firestore.instance.collection('user').document(user.email).snapshots().listen((userI) {
  _fname = userI.data()['FullName'];
  _SSID = userI.data()['SSID'];
  _email = userI.data()['email'];
  _image = userI.data()['image'];
});

Upvotes: 1

Related Questions