Flutter/Dart: Add clutering on google maps using fluster package and provider state management not qorking on zoom in/out

I am working on a flutter/dart project and I’ve created a google map with some markers on it using the google_maps_flutter. Then i wanted to group my markers using clustering and i added the fluster package.

When the screen loads for first time it shows the clusters. When i try to zoom it works and shows the clusters for the current zoom level (the first time), but then if i try to zoom in further it takes me to the initial or previous zoom state with previous clusters.

This is the code part I update the markers based on current zoom level

Blockquote

/// Gets the markers and clusters to be displayed on the map for the current zoom level and
  /// updates state.

  Future<void> _updateMarkers([double updatedZoom]) async {

     if (_clusterManager == null || updatedZoom == _currentZoom){
        print("xxx empty all");
        return;
     }

     if (updatedZoom != null) {
        print("I have current zoom and is: $updatedZoom");
        _currentZoom = updatedZoom;
     }

     setState(ViewState.Busy);

      final updatedMarkers = await MapHelper.getClusterMarkers(
        _clusterManager,
        _currentZoom,
        _clusterColor,
        _clusterTextColor,
        80,
      );

      _markers
        ..clear()
        ..addAll(updatedMarkers);


    setState(ViewState.Idle);

  }

I am using a provider with setState(ViewState.Busy); and setState(ViewState.Idle); and i call an _updateMarkers() method on onCameraMove in order to pass the current zoom level and rebuild my clusters

You can see my full code below:

Blockquote

class LandingPageModel extends BaseModel {

  final OffersService _offersService = locator<OffersService>();
  final MapScreenModel _mapScreenModel = locator<MapScreenModel>();

  bool gpsEnabled = false;

  bool _waitNewClusters = false;

  /// Map loading flag
  bool _isMapLoading = true;

  /// Markers loading flag
  bool _areMarkersLoading = true;

  Location _locationService = new Location();

  Location get locationService => _locationService;

  initialise(BuildContext context) async {
    setState(ViewState.Busy);

    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitUp,
      DeviceOrientation.portraitDown,
    ]);

    await _mapScreenModel.fetchActiveMerchants();
    await _loadGPSAndMap(context);

    setState(ViewState.Idle);
  }

  /// Set of displayed markers and cluster markers on the map
  final Set<Marker> _markers = Set();

  /// Minimum zoom at which the markers will cluster
  final int _minClusterZoom = 0;

  /// Maximum zoom at which the markers will cluster
  final int _maxClusterZoom = 19;

  /// [Fluster] instance used to manage the clusters
  Fluster<MapMarker> _clusterManager;

  /// Current map zoom. Initial zoom will be 15, street level
  double _currentZoom = 5;

  /// Color of the cluster circle
  final Color _clusterColor = Colors.blue;

  /// Color of the cluster text
  final Color _clusterTextColor = Colors.white;

  /// Example marker coordinates
  final List<LatLng> _markerLocations = [
    LatLng(35.133233, 33.356197),
    LatLng(34.776625, 32.394729),
    LatLng(35.703111, 34.564555),
    LatLng(35.151245, 33.310963),
    LatLng(35.141536, 33.374235),
    LatLng(35.161295, 33.35811100000001),
  ];

  /// Gets the markers and clusters to be displayed on the map for the current zoom level and
  /// updates state.

  Future<void> _updateMarkers([double updatedZoom]) async {

     if (_clusterManager == null || updatedZoom == _currentZoom){
        print("xxx empty all");
        return;
     }

     if (updatedZoom != null) {
        print("I have current zoom and is: $updatedZoom");
        _currentZoom = updatedZoom;
     }

     setState(ViewState.Busy);

      final updatedMarkers = await MapHelper.getClusterMarkers(
        _clusterManager,
        _currentZoom,
        _clusterColor,
        _clusterTextColor,
        80,
      );

      _markers
        ..clear()
        ..addAll(updatedMarkers);


    setState(ViewState.Idle);

  }

  void _onMapCreated(GoogleMapController controller) {
    globals.googleMapController.complete(controller);

    setState(ViewState.Busy);

    _isMapLoading = false;

    _initMarkers();
  }

  void _initMarkers() async {
    _clusterManager = await MapHelper.initClusterManager(
      markers,
      _minClusterZoom,
      _maxClusterZoom,
    );

    await _updateMarkers();
  }


  //fluster begin
  final List<MapMarker> markers = [];

  Future _loadGPSAndMap(BuildContext context) async {
    print("hmmm $context");
    gpsEnabled = await _locationService.serviceEnabled();
    if (gpsEnabled) {

      LatLng currentLocation = await _mapScreenModel
          .getUserLocation()
          .catchError((e) => {print(e.toString())});
      BitmapDescriptor icon = await BitmapDescriptor.fromAssetImage(
          ImageConfiguration(size: Size(1, 1)), 'assets/icons/q_pin.png');

      if (currentLocation != null) {
        CameraPosition _initCamera = CameraPosition(
          target: currentLocation,
          zoom: _currentZoom,
        );

        await _mapScreenModel.addAllMarkers(
            context, _mapScreenModel.stores, icon, currentLocation);

        for (LatLng markerLocation in _markerLocations) {

          final BitmapDescriptor markerImage = await BitmapDescriptor.fromAssetImage(
              ImageConfiguration(size: Size(1, 1)), 'assets/icons/q_pin.png');

          markers.add(
            MapMarker(
              id: _markerLocations.indexOf(markerLocation).toString(),
              position: markerLocation,
              icon: markerImage,
            ),
          );
        }

        if(_mapScreenModel.state == ViewState.Busy){
          _waitNewClusters = true;
        }

        if(_mapScreenModel.state == ViewState.Idle){
          _waitNewClusters = false;
        }


print("_waitNewClusters value $_waitNewClusters");
        globals.googleMapsClusters = Scaffold(
        appBar: AppBar(
          title: Text('Markers and Clusters Example'),
        ),
        body: Stack(
          children: <Widget>[
            // Google Map widget
            Opacity(
              opacity: _waitNewClusters ? 0 : 1,
              child: GoogleMap(
                mapType: MapType.normal,
                initialCameraPosition: _initCamera,
                onMapCreated: (controller) => _onMapCreated(controller),
                markers: _markers,
                onCameraMove: (position) => _updateMarkers(position.zoom),
              ),
            ),

            // Map loading indicator
            Opacity(
              opacity: _waitNewClusters ? 1 : 0,
              child: Center(child: CircularProgressIndicator()),
            ),

            // Map markers loading indicator
            if (_waitNewClusters)
              Padding(
                padding: const EdgeInsets.all(8.0),
                child: Align(
                  alignment: Alignment.topCenter,
                  child: Card(
                    elevation: 2,
                    color: Colors.grey.withOpacity(0.9),
                    child: Padding(
                      padding: const EdgeInsets.all(4),
                      child: Text(
                        'Loading',
                        style: TextStyle(color: Colors.white),
                      ),
                    ),
                  ),
                ),
              ),
          ],
        ),
      );


      }
    }
  }
}

Please help!