在颤动中单击时更改折线的颜色

时间:2020-09-24 07:02:09

标签: google-maps flutter dart polyline

我使用flutter polyline插件在flutter中创建了一条折线。现在,我想在用户点击折线时更改其颜色。请帮助我实现这一目标。

1 个答案:

答案 0 :(得分:0)

这是如何在点击时更改Polyline颜色的方法:

首先,您需要使用Polyline classMap<>对象定义为键/值对的集合,这将帮助您稍后确定要单击的折线/轻按,特别是如果您有许多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),
    ...
),