I created a polyline in flutter using flutter polyline plugin. Now I want to change the color of the polyline when user taps on it. Please help me in achieving this.
I created a polyline in flutter using flutter polyline plugin. Now I want to change the color of the polyline when user taps on it. Please help me in achieving this.
Here is how you can change the Polyline color on tap:
First, you will need to define your Polyline object as a collection of key/value pairs using the Map<> class, this will help you later on identifying which polyline is being clicked/tapped on, specially if you have many Polyline objects.
Map<PolylineId, Polyline> _polylines = <PolylineId, Polyline>{};
var pointArray; // var to hold the PolylineOverview
int _polylineIdCounter = 1; // polylineId that you will use for your polylines
Then, you can set your polylines like this:
void _setPolyline() {
pointArray = myPoints.decode(overviewPolylinePointsExample); // use PolyUtil(); to decode polylines
final String polylineIdVal = 'marker_id_$_polylineIdCounter';
_polylineIdCounter++;
final PolylineId polylineId = PolylineId(polylineIdVal);
final Polyline polyline = Polyline(
polylineId: polylineId,
consumeTapEvents: true, // Set to true to make polylines recognize tap events
points: pointArray,
color: Colors.red,
onTap: () {
_handlePolylineTap(polylineId); // function that will handle the color change and will be triggered when the polyline was tapped
});
setState(() {
_polylines[polylineId] = polyline; // Add the polyline to your collection
});
}
From the above code, consumeTapEvents is set to true to make polylines recognize tap events. Then, on the onTap method you will need a function that will handle the changing of color which should be like this:
_handlePolylineTap(PolylineId polylineId) {
setState(() {
final Polyline newPolyline =
_polylines[polylineId].copyWith(colorParam: Colors.blue); // create a new polyline object which has a different color using the colorParam property
_polylines[polylineId] = newPolyline; // add that new polyline object to the list
});
}
Lastly, you can add your polyline list to the GoogleMap() widget like this:
GoogleMap(
...
polylines: Set<Polyline>.of(_polylines.values),
...
),