Kalana Mihiranga
Kalana Mihiranga

Reputation: 488

Values retrieved from firestore only after hot reload in flutter

I am new to flutter. This is what I have done so far(This is not the whole code).As you can see I am trying get some data from firestore in flutter. The problem is that the number value is always zero when I entering to the page. But if I hot reload the page it gives me the correct value. I Why is that? I think it has something to do with future and async. But I don't understand them yet properly.

Widget build(BuildContext context) {

someMethod() {
  return Firestore.instance
      .collection('comments')
      .where("Post", isEqualTo: widget.snapshot.documentID)
      .getDocuments();
}

someMethod().then((QuerySnapshot snapshot) {
  if (snapshot.documents.isNotEmpty) {
    db = snapshot.documents;
  }
});

int number = db?.length ?? 0;
print(number);
}

Upvotes: 0

Views: 998

Answers (1)

hoangquyy
hoangquyy

Reputation: 2063

You have to use setState() to Notify the framework that the internal state of this object has changed.

someMethod().then((QuerySnapshot snapshot) {
  if (snapshot.documents.isNotEmpty) {
    setState(() {
      db = snapshot.documents;
    });
  }
});

Upvotes: 3

Related Questions