我使用 flutter polyline 插件在 flutter 中创建了一条折线。现在我想在用户点击折线时更改折线的颜色。请帮助我实现这一目标。
最佳答案
以下是更改 Polyline
的方法点击颜色:
首先,您需要定义您的Polyline
使用Map<>
作为键/值对集合的对象class ,这将帮助您稍后识别正在单击/点击的多段线,特别是如果您有许多 Polyline
对象。
Map<PolylineId, Polyline> _polylines = <PolylineId, Polyline>{};
var pointArray; // var to hold the PolylineOverview
int _polylineIdCounter = 1; // polylineId that you will use for your polylines
然后,您可以像这样设置折线:
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
});
}
从上面的代码来看,consumeTapEvents
设置为true
使折线识别点击事件。然后,在 onTap
方法,你将需要一个函数来处理颜色的变化,应该是这样的:
_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
});
}
最后,您可以将折线列表添加到 GoogleMap()
像这样的小部件:
GoogleMap(
...
polylines: Set<Polyline>.of(_polylines.values),
...
),
关于google-maps - 在 flutter 中单击时更改折线的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64041116/