I am using below code to get the total number of documents from the firestore collection and then store it to int countDocument
, it does get the value accurately, but when I used to display the same value in the Flutter widget Text Widget
which is nested in Scaffold, upon loading the screen it does not show the value, showing null
only, only upon hot reload it shows the value on the screen.
To represent the value of countDocument
in Text Widget
, I did countDocument.toString()' but still it does not show the value upon initial loading of the screen
How should I resolve it?
void countDocuments() async {
StreamSubscription<QuerySnapshot> _myDoc = await Firestore.instance.collection('users').snapshots().listen((result) {
countDocument = result.documents.length;
print(countDocument);
});
You need to use a StatefulWidget
, then using setState
, you can change the data of the Text
:
void countDocuments() async {
StreamSubscription<QuerySnapshot> _myDoc = await Firestore.instance
.collection('users')
.snapshots()
.listen((result) {
setState(() {
countDocument = result.documents.length;
});
print(countDocument);
});
}
setState
will call the build
method again with the new data. Inside the build
method you can do the following:
Text(countDocument ?? "loading")