Search code examples
fluttergoogle-mapsandroid-manifest

Cannot use Google Maps with Flutter


I am currently working on an application that solves public transport problems through easy navigation.

I am in the very early part of developing the app. I am facing an issue with the Google Maps plugin. I have created an API key on Google Cloud, specifically for Google Maps. The idea with the map is to make it interactive and with markers and pins, but I firstly need to create a map.

I have a simple main.dart class that looks like this (it had more elements before, but I have been trying to make this work without success and therefore deleted everything unnecessary.):

import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MapScreen(),
    );
  }
}

class MapScreen extends StatefulWidget {
  @override
  _MapScreenState createState() => _MapScreenState();
}

class _MapScreenState extends State<MapScreen> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Google Maps in Flutter')),
      body: GoogleMap(
        initialCameraPosition: CameraPosition(
          target: LatLng(37.7749, -122.4194), // San Francisco coordinates
          zoom: 12,
        ),
      ),
    );
  }
}

In my AndroidManifest.xml I have tried adding my key:

<manifest xmlns:android="http://schemas.android.com/apk/res/android">
    <application
        android:label="test1"
        android:name="${applicationName}"
        android:icon="@mipmap/ic_launcher">

          <meta-data
              android:name="com.google.android.geo.API_KEY"
              android:value="ActualAPIKeyIDecidedToHide" />
              
        <activity
            android:name=".MainActivity"
            android:exported="true"
            android:launchMode="singleTop"
            android:theme="@style/LaunchTheme"
            android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
            android:hardwareAccelerated="true"
            android:windowSoftInputMode="adjustResize">

            <!-- Specifies an Android theme to apply to this Activity as soon as
                 the Android process has started. This theme is visible to the user
                 while the Flutter UI initializes. After that, this theme continues
                 to determine the Window background behind the Flutter UI. -->
            <meta-data
              android:name="io.flutter.embedding.android.NormalTheme"
              android:resource="@style/NormalTheme"
              />
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
        <!-- Don't delete the meta-data below.
             This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
        <meta-data
            android:name="flutterEmbedding"
            android:value="2" />
    </application>
    <!-- Required to query activities that can process text, see:
         https://developer.android.com/training/package-visibility?hl=en and
         https://developer.android.com/reference/android/content/Intent#ACTION_PROCESS_TEXT.

         In particular, this is used by the Flutter engine in io.flutter.plugin.text.ProcessTextPlugin. -->
    <queries>
        <intent>
            <action android:name="android.intent.action.PROCESS_TEXT"/>
            <data android:mimeType="text/plain"/>
        </intent>
    </queries>
</manifest>

The apps should run correctly and display a simple map, but instead it is white (except for the app bar), and in my DEBUG CONSOLE I get this error:

V/GoogleMapController( 5590): Controller was disposed before GoogleMap was ready.
E/PlatformViewsController( 5590): Disposing platform view threw an exception
E/PlatformViewsController( 5590): java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.util.LinkedList.isEmpty()' on a null object reference
E/PlatformViewsController( 5590):   at com.google.android.gms.dynamic.DeferredLifecycleHelper.zae(com.google.android.gms:play-services-base@@18.0.1:1)
E/PlatformViewsController( 5590):   at com.google.android.gms.dynamic.DeferredLifecycleHelper.onDestroy(com.google.android.gms:play-services-base@@18.0.1:2)
E/PlatformViewsController( 5590):   at com.google.android.gms.maps.MapView.onDestroy(com.google.android.gms:play-services-maps@@18.2.0:1)
E/PlatformViewsController( 5590):   at io.flutter.plugins.googlemaps.GoogleMapController.destroyMapViewIfNecessary(GoogleMapController.java:914)
E/PlatformViewsController( 5590):   at io.flutter.plugins.googlemaps.GoogleMapController.dispose(GoogleMapController.java:600)
E/PlatformViewsController( 5590):   at io.flutter.plugin.platform.PlatformViewsController$1.dispose(PlatformViewsController.java:256)
E/PlatformViewsController( 5590):   at io.flutter.embedding.engine.systemchannels.PlatformViewsChannel$1.dispose(PlatformViewsChannel.java:150)
E/PlatformViewsController( 5590):   at io.flutter.embedding.engine.systemchannels.PlatformViewsChannel$1.onMethodCall(PlatformViewsChannel.java:58)
E/PlatformViewsController( 5590):   at io.flutter.plugin.common.MethodChannel$IncomingMethodCallHandler.onMessage(MethodChannel.java:267)
E/PlatformViewsController( 5590):   at io.flutter.embedding.engine.dart.DartMessenger.invokeHandler(DartMessenger.java:292)
E/PlatformViewsController( 5590):   at io.flutter.embedding.engine.dart.DartMessenger.lambda$dispatchMessageToQueue$0$io-flutter-embedding-engine-dart-DartMessenger(DartMessenger.java:319)
E/PlatformViewsController( 5590):   at io.flutter.embedding.engine.dart.DartMessenger$$ExternalSyntheticLambda0.run(Unknown Source:12)
E/PlatformViewsController( 5590):   at android.os.Handler.handleCallback(Handler.java:942)
E/PlatformViewsController( 5590):   at android.os.Handler.dispatchMessage(Handler.java:99)
E/PlatformViewsController( 5590):   at android.os.Looper.loopOnce(Looper.java:201)
E/PlatformViewsController( 5590):   at android.os.Looper.loop(Looper.java:288)
E/PlatformViewsController( 5590):   at android.app.ActivityThread.main(ActivityThread.java:7872)
E/PlatformViewsController( 5590):   at java.lang.reflect.Method.invoke(Native Method)
E/PlatformViewsController( 5590):   at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
E/PlatformViewsController( 5590):   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:936)
D/EGL_emulation( 5590): app_time_stats: avg=22221.97ms min=118.97ms max=44324.98ms count=2

════════ Exception caught by widgets library ═══════════════════════════════════
The following NoSuchMethodError was thrown building MyApp(dirty):
No constructor '' declared in class 'null'.
Receiver: null
Tried calling: new ()

The relevant error-causing widget was:
    MyApp MyApp:file:///C:/Users/alexa/OneDrive/Skrivbord/test1/lib/main.dart:4:23

When the exception was thrown, this was the stack:
#0      NoSuchMethodError._throwNew (dart:core-patch/errors_patch.dart:191:5)
#1      MyApp.build (package:test1/main.dart:10:13)
#2      StatelessElement.build (package:flutter/src/widgets/framework.dart:5550:49)

I would also like to mention that I am using Visual Studio on Windows 11 and using an emulator of a Pixel 8 Pro.

I have tried:

  • different guides online, hoping that it would work.

  • creating a new project, and pasting in the same thing. Did not work.

  • flutter clean and flutter run, also did not work.

  • Reimporting Google Maps multiple times. Did not work either.

  • Changing settings.gradle minSdkVersion. Solved one error, but I now get this one instead,


Solution

  • The code you provided works perfectly well. Anyway, try the below code if that solves your problem.

    Create a Google Map Controller

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

    Then, Within the GoogleMap() Widget, utilize this controller by assigning it to the onMapCreated parameter.

    GoogleMap(
        initialCameraPosition: CameraPosition(
          target: LatLng(37.7749, -122.4194), // San Francisco coordinates
          zoom: 12,
        ),
       onMapCreated: (GoogleMapController c) {
                  _controller.complete(c);  // <--- Assign controller
              },
      ),