Flutter rebuild only current's location point on map (setState)

Viewed 919

I am trying to implement user's current location on the map using Flutter and few of plugins (flutter_map, location, etc.) But I have a performance issues probably caused by setState() method, which invokes build() function every time some value appears in stream.

What I need is to rebuild only one part in the FlutterMap widget, but there are few problems with this. I would normally use separate stateful widget, but PolyLineOptions accept only List of Polyline type.

Here is my code (build function)

  Widget build(BuildContext context) {
    return Stack(
      children: <Widget>[
        FlutterMap(
          options: MapOptions(
            center: LatLng(lat, lng),
            zoom: 15,
            minZoom: 14,
            maxZoom: 18,
          ),
          layers: [
            TileLayerOptions(
              urlTemplate: mapUrl,
              subdomains: ['a', 'b', 'c'],
            ),
   ->       PolylineLayerOptions(polylines: currentPosition),
            MarkerLayerOptions(
              markers: parkingLotsMarkers,
            ),
          ],
        ),
      ],
    );
  }

Stream with current location - everytime new value appears, array with marker will update and with this, all widget tree is rebuild aswell.

  void _getCurrentLocation() {
    subscription = location.onLocationChanged().listen((l) {
      print("listenin");
      setState(() {
        currentPosition = [
          Polyline(
            points: [LatLng(l.latitude, l.longitude)],
            strokeWidth: 8,
            color: Color.fromRGBO(33, 150, 243, 1),
          ),
          Polyline(
            points: [LatLng(l.latitude, l.longitude)],
            strokeWidth: 30,
            color: Color.fromRGBO(33, 150, 243, .2),
          )
        ];
      });
    });
  }

Do you guys have any idea, how to solve this issue? Thanks a lot!

0 Answers
Related