无法将 Google 地图与 Flutter 结合使用

问题描述 投票:0回答:1

我目前正在开发一款通过轻松导航解决公共交通问题的应用程序。

我正处于开发应用程序的早期阶段。我遇到了 Google 地图插件的问题。我在 Google Cloud 上创建了一个 API 密钥,专门用于 Google 地图。 地图的想法是使其具有交互性并带有标记和图钉,但我首先需要创建一张地图。

我有一个简单的 main.dart 类,如下所示(它之前有更多元素,但我一直在尝试使这项工作成功,因此删除了所有不必要的内容。):

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,
        ),
      ),
    );
  }
}

在我的 AndroidManifest.xml 中,我尝试添加我的密钥:

<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>

应用程序应该正确运行并显示一个简单的地图,但它是白色的(应用程序栏除外),并且在我的调试控制台中我收到此错误:

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)

我还想提一下,我正在 Windows 11 上使用 Visual Studio 并使用 Pixel 8 Pro 的模拟器。

我已经尝试过:

  • 网上有不同的指南,希望它能起作用。

  • 创建一个新项目,然后粘贴相同的内容。没用。

  • flutter clean 和 flutter run,也没用。

  • 多次重新导入 Google 地图。也没有用。

  • 更改settings.gradle minSdkVersion。解决了一个错误,但我现在得到了这个错误,

flutter google-maps android-manifest
1个回答
0
投票

您提供的代码运行良好。无论如何,如果可以解决您的问题,请尝试以下代码。

创建 Google 地图控制器

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

然后,在 GoogleMap() 小部件中,通过将其分配给 onMapCreated 参数来使用此控制器。

GoogleMap(
    initialCameraPosition: CameraPosition(
      target: LatLng(37.7749, -122.4194), // San Francisco coordinates
      zoom: 12,
    ),
   onMapCreated: (GoogleMapController c) {
              _controller.complete(c);  // <--- Assign controller
          },
  ),
© www.soinside.com 2019 - 2024. All rights reserved.