We use cookies to give you the best experience on our website. If you continue to browse, then you agree to our privacy policy and cookie policy. Image for the cookie policy date
close icon

setState() not working on SfMaps

layers: [ MapTileLayer( controller: _mapTileLayerController, urlTemplate: 'https://tile.openstreetmap.org/{z}/{x}/{y}.png', zoomPanBehavior: _mapZoomPanBehavior, initialMarkersCount: gpsStoppageHistory.length, markerBuilder: (BuildContext context, int index) { print( "gps stops length is ${gpsStoppageHistory.length}, $index"); if (index == gpsStoppageHistory.length - 1) { return MapMarker( latitude: gpsStoppageHistory[index] .latitude, longitude: gpsStoppageHistory[index] .longitude, child: Image.asset( 'assets/icons/truckPin.png', height: 80)); } else { return MapMarker( latitude: gpsStoppageHistory[index].latitude, longitude: gpsStoppageHistory[index].longitude, iconType: MapIconType.circle, child: CircleAvatar( backgroundColor: red, foregroundColor: white, child: Center( child: Text((index + 1).toString())), ), ); } }, sublayers: [ MapPolylineLayer( polylines: { MapPolyline( points: polylineCoordinates2, color: Color.fromRGBO(0, 102, 255, 1.0), width: 6.0, ) }, ), ], ), ], ),

This is the code for plotting different markers for tracking the location history of a vehicle. Here the data source which is used to plot markers is gpsStoppageHistory, which is a list mapped from an API, and when I click a button, this list is updated with some additional values, and then setState() is called. Hence after the setState() function, the map is supposed to use the updated value of the gpsStoppageHistory, but the value is not getting updated in the map, it's still showing the old set of markers before updating the list.

3 Replies

IR Indumathi Ravi Syncfusion Team November 21, 2022 11:32 AM

Hi Neha,

In the SfMaps widget, the markers will not get updated by calling the setState method on the button click based on the updated list.

For adding, deleting, updating, and clearing the markers in the SfMaps widget, you can set the instance MapTileLayerControllers for the MapTileLayer and use its methods such as insertMarkerupdateMarkersremoveMarkerAt, and clearMarkers to dynamically add, delete or update the markers in the chart.

We have also created a simple maps sample with a tile layer in which we have added some markers in the maps by default using a list whose items consist of the marker’s latitude and longitude values and have placed a button below the maps widget, and in its onPressed event, we have randomly added some additional latitude and longitude values for the marker that is to be added newly to the list and called the insertMarker method with the index of the newly added marker values in the list. As a result, each time you click the button, a new marker will be added to the maps at random.