Reputation: 73
Hi I am using this code here to retrieve data from Firestore. The data is in a Map
and here is the picture of my Firestore.
And here is my code when I retrieve from Firestore
Future <void> getRoute() async{
Firestore.instance.collection('routes').snapshots().listen((RouteData) {
if(RouteData.documents.isNotEmpty){
for (int i = 0; i < RouteData.documents.length; i++){
_getPolyline(RouteData.documents[i].data, RouteData.documents[i].documentID);
}
}
});
setState(() {
});
}
void _getPolyline(info, infoID) async{
print(info);}
When Im printing the info
it will display the data many times.
here is the result. As you can see it starts off in
test
then test1
then test
again and repeated for some time. Is there something wrong with my code? Thank you in advance.
Upvotes: 0
Views: 530
Reputation: 1294
Calling setState
will trigger a rebuild of your widget. What i think is happening is that when getRoute()
u are also triggering your build function which will trigger getRoute()
to run again.
solution:
make sure your function is not being triggered during a build. you can do this by triggering your function only once in initState
Either that or because u are using snapshots().listen
. this will listen to any changes that happen on that collection.
solution:
use .get()
instead of .listen()
To read a collection or document once, call the Query.get or DocumentReference.get methods. In the below example a FutureBuilder is used to help manage the state of the request: https://firebase.flutter.dev/docs/firestore/usage/#one-time-read
Upvotes: 1