Rafael Zablah
Rafael Zablah

Reputation: 35

Flutter - Firestore is returning null data to a map on inistate statement

Here is my code:

void initState() {
 likesRef = FirebaseFirestore.instance.collection('likes').doc(currentUser);
 super.initState();
 likesRef.get().then((value) => data = value.data());
 postRef = FirebaseFirestore.instance.collection('Products');
}


@override
Widget build(BuildContext context) {
 print('data $data');

I'm getting null data but in firestore I have data:

enter image description here

Upvotes: 0

Views: 420

Answers (1)

Peter Haddad
Peter Haddad

Reputation: 80952

Try the following:

void initState() {
 super.initState();
 likesRef = FirebaseFirestore.instance.collection('likes').doc(currentUser);
 likesRef.get().then((value){
   data = value.data();
    setState(() {});
  });
 postRef = FirebaseFirestore.instance.collection('Products');
}

When overriding always call the super method first when overriding to make sure the parent class method is being called before doing anything else in your code. Then after retrieving the data you can call setState to rebuild the widget tree with the data value. The other way is to use futurebuilder widget.

Upvotes: 2

Related Questions