fetching data from firebase firestore using flutter

Viewed 20

I have an application where i need to get user real time location and push it into database using geoflutterfire , the code is working but i do not understand why it keeps generating multiple documents , while on the other side using the same plugin , we should use only collection reference , can any help me with this , Thank you

  • Picture showing pushing data into firestore using geoflutterfire plugin ( but why it keeps generating new documents , i just want to solely update the same document )

enter image description here

  • Push data into firebase firestore
void updateDriverLocation(){
   Fluttertoast.showToast(msg: "Called");
   geoFlutterFire = Geoflutterfire();
   if(latitude != 0.0 && longitude != 0.0){
      GeoFirePoint geoFirePoint = geoFlutterFire.point(latitude: latitude, longitude: longitude);
      var map = HashMap<String,Object>();
      map['name'] = _firebaseAuth.currentUser!.uid;
      map['position'] = geoFirePoint.data;
      _firebaseFirestore.collection("Drivers").add(map);
   }
 }
  • get data from firebase firebase

   void getDrivers(){
    geoFlutterFire = Geoflutterfire();
    GeoFirePoint geoFirePoint = GeoFirePoint(latitude, longitude);
    var ref = _firebaseFirestore.collection('Drivers');
    var locations = geoFlutterFire.collection(collectionRef: ref).within(center: geoFirePoint, radius: maxRadius, field: 'position');
    locations.listen((List<DocumentSnapshot> documentList) {
       for (var documentSnapshot in documentList) {
         Map<String,Object> map = documentSnapshot.get('geopoint');
         double lat = map['latitude'] as double;
         double lon = map['longitude'] as double;
         //_list.add(LatLng(lat, lon));
         markers.add(Marker(
                    markerId: MarkerId(DateTime.now().millisecond.toString()),
                    position: LatLng(lat,lon),
                    icon: BitmapDescriptor.defaultMarker
                ));
       }
    });
  }

  • This is how i'm trying to listen to the data returned from firestore
1 Answers
_firebaseFirestore.collection("Drivers").add(map);

The .add() method creates a new document with a random ID every time. If you want to update a specific document then you must use update() on a DocumentReference. Try the following:

_firebaseFirestore.collection("Drivers").doc(_firebaseAuth.currentUser!.uid).update(map);

This will update current drivers document only.


GeoFlutterFire has the following to specify DocID:

geoRef.setDoc(String id, var data, {bool merge})
Related