Flutter google map how to instanciate a GoogleMapController outside of the GoogleMap's widget onCreated function for testings?

Viewed 2439

I'm using plugin google_maps_flutter 1.2.0, and i want to instanciate a GoogleMapController for testing some bloc's event, where the controller's value can't be null. Unfortunalty, i don't know how to do it, because to my knows, GoogleMapController can't be instanciate outside of the function 'OnCreated' of the GoogleMap() Widget.

 GoogleMap(onMapCreated: (GoogleMapController controller) {
                         // Can only be instanciate here
                        },
          );

It's impossible to do something like this :

  GoogleMapController controller = new GoogleMapsController();

I can only do this, and controller is null :

 GoogleMapController controller;

I tried multiple thing but nothing is working, can someone help me ?

3 Answers

First, GoogleMapController _googleMapController in your _WidgetState.
Then

GoogleMap(onMapCreated: (GoogleMapController controller) {
        _googleMapController = controller;
    }
);  

After Google Map Created, you can use _googleMapController everywhere in your widget.

You can use use _googleMapController? = controller; before the build method the make a little if statement (_googleMapController != null) where you want to use your method or what ever you want to do with the instance.

If you are using a Flutter 2.5.3 and later you can add a late in front of the variable declaration i.e late GoogleMapController _googleMapController;

In your googlemap widget you can use the variable as normal onMapCreated: (controller) => _googleMapController = controller,

Related