Flutter - auto-refresh marker's icon on map after a period of time

2,054

Try to add a Listener:

BitmapDescriptor customFreeLotIcon, customOccupiedLotIcon;
Future<List<Marker>> _createMarkersForLotsAndParkings() async{
   List<Marker> markersList = [];
   int markerId = 0;
    QuerySnapshot subDocuments = await parkingDocReference.collection("lots").get();
    List<DocumentSnapshot> subDocumentsSnapshots = subDocuments.documents;
    for (DocumentSnapshot subDoc in subDocumentsSnapshots){
         String subDocId = subDoc.documentID;
         DocumentSnapshot snapshot = await parkingDocReference.collection("lots")
         .document(subDocId).snapshots()
        .listen((DocumentSnapshot documentSnapshot) async {
      Map<String, dynamic> document = documentSnapshot.data();
            print(document['location'].latitude);
            markersList.add(
              Marker(
                  markerId:MarkerId(markerId.toString()),
                  position: LatLng(document['location'].latitude,
                      document['location'].longitude),
                  onTap: () => _changeMap(LatLng(
                     document['location'].latitude,
                      document['location'].longitude)),
                  icon: document['status'] == true ? customOccupiedLotIcon : customFreeLotIcon ),
            );
            markerId++;   
}   
     }
}
return Future.value(markersList);

}


 createCustomImageForParkingsMarkers(context){
    if (customFreeLotIcon == null) {
      ImageConfiguration configuration = createLocalImageConfiguration(context);
      BitmapDescriptor.fromAssetImage(configuration, 'assets/freeLots.png')
          .then((icon) {
        setState(() {
          customFreeLotIcon = icon;
        });
      });
    }
    else if (customOccupiedLotIcon == null) {
      ImageConfiguration configuration = createLocalImageConfiguration(context);
      BitmapDescriptor.fromAssetImage(configuration, 'assets/occupiedLots.png')
          .then((icon) {
        setState(() {
          customOccupiedLotIcon = icon;
        });
      });
    }
  }

Add Setstate() here:

setState(() {
      markersList.add(
        Marker(
            markerId:MarkerId(markerId.toString()),
            position: LatLng(document['location'].latitude,
                document['location'].longitude),
            onTap: () => _changeMap(LatLng(
                document['location'].latitude,
                document['location'].longitude)),
            icon: document['status'] == true ? customOccupiedLotIcon : customFreeLotIcon ),
      );
      markerId++;
    });
Share:
2,054
Andreea Purta
Author by

Andreea Purta

Updated on December 24, 2022

Comments

  • Andreea Purta
    Andreea Purta over 1 year

    I have some markers and the icons of the markers change based on a firebase field (called status). status is a bool (true/false). This status value changes in the database very often by an external application, so I need to be able to update the icon based on the current value of the field. How can I update the markers on my UI automatically?

    Here's my code:

    BitmapDescriptor customFreeLotIcon, customOccupiedLotIcon;
    Future<List<Marker>> _createMarkersForLotsAndParkings() async{
       List<Marker> markersList = [];
       int markerId = 0;
        QuerySnapshot subDocuments = await parkingDocReference.collection("lots").get();
        List<DocumentSnapshot> subDocumentsSnapshots = subDocuments.documents;
        for (DocumentSnapshot subDoc in subDocumentsSnapshots){
             String subDocId = subDoc.documentID;
             DocumentSnapshot snapshot = await parkingDocReference.collection("lots")
             .document(subDocId).get();
                print(snapshot.get('location').latitude);
                markersList.add(
                  Marker(
                      markerId:MarkerId(markerId.toString()),
                      position: LatLng(snapshot.get('location').latitude,
                          snapshot.get('location').longitude),
                      onTap: () => _changeMap(LatLng(
                          snapshot.get('location').latitude,
                          snapshot.get('location').longitude)),
                      icon: snapshot.get('status') == true ? customOccupiedLotIcon : customFreeLotIcon ),
                );
                markerId++;      
         }
    }
    return Future.value(markersList);
    
    }
    
    
     createCustomImageForParkingsMarkers(context){
        if (customFreeLotIcon == null) {
          ImageConfiguration configuration = createLocalImageConfiguration(context);
          BitmapDescriptor.fromAssetImage(configuration, 'assets/freeLots.png')
              .then((icon) {
            setState(() {
              customFreeLotIcon = icon;
            });
          });
        }
        else if (customOccupiedLotIcon == null) {
          ImageConfiguration configuration = createLocalImageConfiguration(context);
          BitmapDescriptor.fromAssetImage(configuration, 'assets/occupiedLots.png')
              .then((icon) {
            setState(() {
              customOccupiedLotIcon = icon;
            });
          });
        }
      }
    
  • Andreea Purta
    Andreea Purta over 3 years
    Hi @Amon Chowdhury! On this line code DocumentSnapshot snapshot = await parkingDocReference.collection("lots").document(subDocId).sn‌​apshots().listen((Do‌​cumentSnapshot documentSnapshot) async { code I get this error: A value of type 'StreamSubscription<DocumentSnapshot>' can't be assigned to a variable of type 'DocumentSnapshot'. Try changing the type of the variable, or casting the right-hand type to 'DocumentSnapshot'. snipboard.io/k37wQP.jpg
  • Andreea Purta
    Andreea Purta over 3 years
    I tried to change that in : StreamSubscription<DocumentSnapshot> snapshot = await parkingDocReference.collection("lots").document(subDocId).sn‌​apshots().listen((Do‌​cumentSnapshot documentSnapshot) async { but the pins wont update
  • Amon C
    Amon C over 3 years
    use setsate inside the listener
  • Andreea Purta
    Andreea Purta over 3 years
    Can you please tell me how? I am a beginner in dart and flutter :(
  • Andreea Purta
    Andreea Purta over 3 years
    Thank you very much! Now I understand what you meant by saying to use setstate inside the listener!
  • Amon C
    Amon C over 3 years
    Welcome!! Happy Coding