0

`I'm working on google map, my task is to draw polygons from firebase real-time database, using stream to change polygons while real-time database values affected, the data would change but Google Map not rendering on those changes.

stream class

class RealtimeData {
  final realtimeDataController = StreamController.broadcast();

  Stream get getStream => realtimeDataController.stream;

  final databaseReference = FirebaseDatabase.instance.ref('farms/100');


  bool automation = false;
  LatLng? center;
  List<LatLng> farmBoundary = [];
  Set<Polygon> polygon = HashSet<Polygon>();
  Set<Marker> marker = HashSet<Marker>();

  getData() {
    dynamic data;
    Stream<DatabaseEvent> stream = databaseReference.onValue;
    stream.listen((DatabaseEvent event) {
      print('Event Type: ${event.type}'); // DatabaseEventType.value;
      print('Snapshot: ${event.snapshot}'); // DataSnapshot
      data = event.snapshot.value;
      print(data['plots']);
      setFormBoundary(data['boundary']);
      setCenterLatLng();
      setAutomation(data['automation']);
      setPlots(data['plots']);
    });
  }

  void setAutomation(value) {
    automation = value == 0 ? false : true;
    realtimeDataController.sink.add(automation);
  }

  void setFormBoundary(List boundary) {
    List<LatLng> temp = [];
    for (int i = 0; i < boundary.length; i++) {
      LatLng location = LatLng(boundary[i]['lat'], boundary[i]['lng']);
      if (boundary.isNotEmpty) {
        temp.add(location);
        farmBoundary.add(temp[i]);
      }
    }
    realtimeDataController.sink.add(farmBoundary);
  }

  void setPlots(List plots) {
    for (var element in plots) {
      String fillColor = element["fillColor"];
      String strokeColor = element["strokeColor"];
      List plot = element['coords'];
      List<LatLng> temp = [];
      for (int i = 0; i < plot.length; i++) {
        LatLng location = LatLng(plot[i]['lat'], plot[i]['lng']);
        temp.add(location);
      }
      marker.addLabelMarker(LabelMarker(
        flat: true,
        label: element["plot_name"],
        markerId: MarkerId(element["plot_id"].toString()),
        position: setCenterPlotLatLng(temp),
        backgroundColor: Colors.transparent,
        anchor: const Offset(0.5, 0.25),
        textStyle: const TextStyle(fontSize: 14, fontFamily: 'ubuntu'),
      ));
      Future.delayed(const Duration(milliseconds: 250), () {
        setPolygon(temp, fillColor, strokeColor);
      });
    }
    realtimeDataController.sink.add(marker);
  }

  void setCenterLatLng() {
    double totalLat = 0;
    double totalLng = 0;
    for (int i = 0; i < farmBoundary.length; i++) {
      totalLat += farmBoundary[i].latitude;
      totalLng += farmBoundary[i].longitude;
    }
    center = LatLng(
        (totalLat / farmBoundary.length), (totalLng / farmBoundary.length));
    setPolygon(farmBoundary);

    realtimeDataController.sink.add(center);
  }

  LatLng setCenterPlotLatLng(points) {
    double totalLat = 0;
    double totalLng = 0;
    for (int i = 0; i < points.length; i++) {
      totalLat += points[i].latitude;
      totalLng += points[i].longitude;
    }
    return LatLng((totalLat / points.length), (totalLng / points.length));
  }

  void setPolygon(points, [fillColor = "", strokeColor = ""]) {
    Color fill = Colors.transparent;
    Color stroke = Colors.yellow;
    if (fillColor.isNotEmpty) {
      final hexCode = fillColor.replaceAll('#', '');
      fill = Color(int.parse('FF$hexCode', radix: 16));
    }
    if (strokeColor.isNotEmpty) {
      final hexCode = strokeColor.replaceAll('#', '');
      stroke = Color(int.parse('FF$hexCode', radix: 16));
    }
    polygon.add(Polygon(
      polygonId: PolygonId(points.toString()),
      points: points,
      visible: true,
      strokeWidth: 1,
      fillColor: fill,
      strokeColor: stroke,
    ));
    realtimeDataController.sink.add(polygon);
  }

  void dispose() {
    realtimeDataController.close(); 
  }
}

final bloc = RealtimeData();

google map widget

Widget loadMap(width, height) {
    return StreamBuilder(
        stream: bloc.getStream,
        builder: (context, snapshot) {
          return Padding(
              padding:
                  EdgeInsets.only(top: height * 0.01, bottom: height * 0.01),
              child: SizedBox(
                height: height * 0.25,
                width: width,
                child: GoogleMap(
                    initialCameraPosition:
                        CameraPosition(target: bloc.center!, zoom: 17),
                    mapType: MapType.hybrid,
                    indoorViewEnabled: false,
                    buildingsEnabled: false,
                    zoomControlsEnabled: false,
                    zoomGesturesEnabled: true,
                    polygons: bloc.polygon,
                    markers: bloc.marker,
                    gestureRecognizers: Set()
                      ..add(Factory<PanGestureRecognizer>(
                          () => PanGestureRecognizer()))
                      ..add(Factory<ScaleGestureRecognizer>(
                          () => ScaleGestureRecognizer()))
                      ..add(Factory<TapGestureRecognizer>(
                          () => TapGestureRecognizer()))
                      ..add(Factory<VerticalDragGestureRecognizer>(
                          () => VerticalDragGestureRecognizer()))),
              ));
        });
  }

google map polygons color didn't change when data changed

0 Answers0