'In Flutter Google Maps how do I add and remove markers based on a realtime database listener?

I've read numerous docs, posts, etc. and cannot seem to get things to work.

I have a realtime database listener that provides lat/long coordinates, inside a FirebaseAnimatedList. When coordinates are provided, I want it to place a marker on the map. When coordinates do not exist, the marker should be removed (I haven't gotten that far in the code, I can't even get the markers to show up).

I create the markers and controller like this:

Set<Marker> markers = Set();
final Completer<GoogleMapController> _controller = Completer();

I have the following code inside the FirebaseAnimatedList to create the marker:

Marker userMarker;
              userMarker = Marker(
                markerId: MarkerId(id),
                position: LatLng(
                    lat, lon),
              );

              markers.add(userMarker);

And I call GoogleMap inside the build widget like this:

GoogleMap(
              mapType: MapType.normal,
              myLocationEnabled: true,
              myLocationButtonEnabled: true,
              compassEnabled: true,
              initialCameraPosition: _kGooglePlex,
              onMapCreated: (GoogleMapController controller) {
                _controller.complete(controller);
              },
              markers: markers,
            ),

When the listener picks up coordinates, no marker is added. If the listener has coordinates already when the map is created, still no marker is added. How do I get a marker to be added and removed based on the listener?



Solution 1:[1]

GoogleMap Widget renders the map and markers during build. If there are changes on your List of Markers, you'd need to rebuild the Widget. One approach that you can use to store your markers is by using Map

Map<MarkerId, Marker> markers = <MarkerId, Marker>{};

...and calling setState() to store changes in the Map, and to rebuild the GoogleMap Widget.

setState(() {
  markers[markerId] = marker;
});

Then set the Markers on GoogleMap.markers()

GoogleMap(
  ...
  markers: markers.values.toSet(),
)

You can check this complete sample provided by google_maps_flutter plugin as a guide.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Omatt