Search code examples
fluttergoogle-maps-flutter

How to dispose Flutter google map's controller


I was using google_maps_flutter library in my project. While i hot reload the map or back to map from another view then it crashes with message :

Exception has occurred.
PlatformException (PlatformException(error, java.lang.IllegalStateException: Trying to create an already created platform view, view id: 0
    at io.flutter.plugin.platform.PlatformViewsController$1.createPlatformView(PlatformViewsController.java:85)
    at io.flutter.embedding.engine.systemchannels.PlatformViewsChannel$1.create(PlatformViewsChannel.java:96)

So i was trying to dispose the map and its controller. i got a code snippet to dispose in this article So i added this code snippet:

@override
  void dispose() {
    _disposeController();
    super.dispose();
  }

  Future<void> _disposeController() async{
    final GoogleMapController controller = await _controller.future;
    //controller.dispose();
  }

but uncommenting last line was giving this error:

 The method 'dispose' isn't defined for the class 'GoogleMapController'.
Try correcting the name to the name of an existing method, or defining a method named 'dispose'.

then how can i dispose the controller?


Solution

  • I just faced the same trouble and realized, that they drastically changed the GoogleMapController implementation between this medium article and the current version.

    Also, the readme on the package could be outdated, I used the examples from the package itself:

    e.g. https://github.com/flutter/plugins/blob/master/packages/google_maps_flutter/google_maps_flutter/example/lib/animate_camera.dart

    They seem to work really well.

    Update

    It seems like they have gotten rid of the Completer way and in their examples they do not need this construction anymore.

    That means: Use the GoogleMapController directly without a completer:

    GoogleMapController mapController;
    // instead of 
    // GoogleMapController mapController;
    

    just assign to this variable onMapCreated:

    onMapCreated: (GoogleMapController controller) {
      _controller.complete(controller);
    },
    

    You can then use this controller without awaiting the future.

    mapController.animateCamera(
      CameraUpdate.newLatLng(
        const LatLng(56.1725505, 10.1850512),
      ),
    );
    

    I have not seen any need to dispose this instance, it is not implemented anymore through the ChangeNotifier() class.