简体   繁体   中英

Duplicated Data from Firestore

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.

1个

2个

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM