Home > Back-end >  Google maps controller cannot be initialized, flutter 2.8.1 google_maps_flutter 2.1.1
Google maps controller cannot be initialized, flutter 2.8.1 google_maps_flutter 2.1.1

Time:03-02

Here i'am asking again on Stack Overflow :), when i try to make a GoogleMapsController variable it show this

Non-nullable instance field 'googleMapController' must be initialized.
Try adding an initializer expression, or a generative constructor that initializes it, or mark it 'late'

my controller

GoogleMapController googleMapController;

enter image description here

and if i use this

Completer<GoogleMapController> _controller = Completer();

the Completer is not defined

and if i use

late GoogleMapController googleMapController;

it will occurs error when i use the controller and say

LateError (LateInitializationError: Field 'googleMapController' has not been initialized.)

i don't understand why people on youtube didn't get any error like this

CodePudding user response:

Because of null safety your variable must be initialzied when created,

If you are using a Flutter 2.5.3 and later you can use late to tell it that it will be initialized after being created but before being used (that is why people on YouTube didn't get any error like this if they didn't use late ) :

  late final Completer<GoogleMapController> _controller = Completer();

CodePudding user response:

here is the full example for you using same versions flutter 2.8.1 , google_maps_flutter 2.1.1

class MapController extends StatefulWidget {
  const MapController({Key? key}) : super(key: key);

  @override
  _MapControllerState createState() => _MapControllerState();
}

class _MapControllerState extends State<MapController> {
  late final Completer<GoogleMapController> _controller = Completer();

  static CameraPosition get _kGooglePlex => const CameraPosition(
    target: LatLng(37.42796133580664, -122.085749655962),
    zoom: 14.4746,
  );

  static CameraPosition get _kLake => const CameraPosition(
      bearing: 192.8334901395799,
      target: LatLng(37.43296265331129, -122.08832357078792),
      tilt: 59.440717697143555,
      zoom: 19.151926040649414);

  @override
  Widget build(BuildContext context) {
    return  Scaffold(
      body: GoogleMap(
        mapType: MapType.hybrid,
        initialCameraPosition: _kGooglePlex,
        onMapCreated: (GoogleMapController controller) {
          _controller.complete(controller);
        },
      ),
      floatingActionButton: FloatingActionButton.extended(
        onPressed: _goToTheLake,
        label: const Text('To the lake!'),
        icon: const Icon(Icons.directions_boat),
      ),
    );
  }

  Future<void> _goToTheLake() async {
    final GoogleMapController controller = await _controller.future;
    controller.animateCamera(CameraUpdate.newCameraPosition(_kLake));
  }
  • Related