如何在Flutter中集成Mapbox Map SDK?

piok6c0g  于 2023-05-08  发布在  Flutter
关注(0)|答案(1)|浏览(92)

我是一个初学者Flutter developer,并试图将Mapbox SDK集成到Flutter。我使用了Mapbox for Android的官方文档,做了所有的事情,但Map仍然不起作用。
offical doc

这是我的错误:

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:checkDebugDuplicateClasses'.
> A failure occurred while executing com.android.build.gradle.internal.tasks.CheckDuplicatesRunnable
   > Duplicate class com.mapbox.android.core.location.LocationEngine found in modules jetified-common-23.4.0-runtime (com.mapbox.common:common:23.4.0) and jetified-mapbox-android-core-5.0.0-runtime (com.mapbox.mapboxsdk:mapbox-android-core:5.0.0)
     Duplicate class com.mapbox.android.core.location.LocationEngineCallback found in modules jetified-common-23.4.0-runtime (com.mapbox.common:common:23.4.0) and jetified-mapbox-android-core-5.0.0-runtime (com.mapbox.mapboxsdk:mapbox-android-core:5.0.0)
     Duplicate class com.mapbox.android.core.location.LocationEngineProvider found in modules jetified-common-23.4.0-runtime (com.mapbox.common:common:23.4.0) and jetified-mapbox-android-core-5.0.0-runtime (com.mapbox.mapboxsdk:mapbox-android-core:5.0.0)
     Duplicate class com.mapbox.android.core.location.LocationEngineRequest found in modules jetified-common-23.4.0-runtime (com.mapbox.common:common:23.4.0) and jetified-mapbox-android-core-5.0.0-runtime (com.mapbox.mapboxsdk:mapbox-android-core:5.0.0)
     Duplicate class com.mapbox.android.core.location.LocationEngineRequest$1 found in modules jetified-common-23.4.0-runtime (com.mapbox.common:common:23.4.0) and jetified-mapbox-android-core-5.0.0-runtime (com.mapbox.mapboxsdk:mapbox-android-core:5.0.0)
     Duplicate class com.mapbox.android.core.location.LocationEngineRequest$Builder found in modules jetified-common-23.4.0-runtime (com.mapbox.common:common:23.4.0) and jetified-mapbox-android-core-5.0.0-runtime (com.mapbox.mapboxsdk:mapbox-android-core:5.0.0)
     Duplicate class com.mapbox.android.core.location.LocationEngineResult found in modules jetified-common-23.4.0-runtime (com.mapbox.common:common:23.4.0) and jetified-mapbox-android-core-5.0.0-runtime (com.mapbox.mapboxsdk:mapbox-android-core:5.0.0)
     Duplicate class com.mapbox.android.core.permissions.PermissionsListener found in modules jetified-common-23.4.0-runtime (com.mapbox.common:common:23.4.0) and jetified-mapbox-android-core-5.0.0-runtime (com.mapbox.mapboxsdk:mapbox-android-core:5.0.0)
     Duplicate class com.mapbox.android.core.permissions.PermissionsManager found in modules jetified-common-23.4.0-runtime (com.mapbox.common:common:23.4.0) and jetified-mapbox-android-core-5.0.0-runtime (com.mapbox.mapboxsdk:mapbox-android-core:5.0.0)
     Duplicate class com.mapbox.android.core.permissions.PermissionsManager$AccuracyAuthorization found in modules jetified-common-23.4.0-runtime (com.mapbox.common:common:23.4.0) and jetified-mapbox-android-core-5.0.0-runtime (com.mapbox.mapboxsdk:mapbox-android-core:5.0.0)

     Go to the documentation to learn how to <a href="d.android.com/r/tools/classpath-sync-errors">Fix dependency resolution errors</a>.

gradle.properties 文件:

org.gradle.jvmargs=-Xmx1536M
android.useAndroidX=true
android.enableJetifier=true
MAPBOX_DOWNLOADS_TOKEN=checked this

styles.xml文件

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- Theme applied to the Android Window while the process is starting when the OS's Dark Mode setting is off -->
    <style name="LaunchTheme" parent="@android:style/Theme.Light.NoTitleBar">
        <!-- Show a splash screen on the activity. Automatically removed when
             the Flutter engine draws its first frame -->
        <item name="android:windowBackground">@drawable/launch_background</item>
    </style>
    <!-- Theme applied to the Android Window as soon as the process has started.
         This theme determines the color of the Android Window while your
         Flutter UI initializes, as well as behind your Flutter UI while its
         running.

         This Theme is only used starting with V2 of Flutter's Android embedding. -->
    <style name="NormalTheme" parent="@android:style/Theme.Light.NoTitleBar">
        <item name="android:windowBackground">?android:colorBackground</item>
        
    </style>
    <string name="mapbox_access_token">checked this</string>
</resources>

AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.mapbox_try2">
     <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
      <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
   <application
        android:label="mapbox_try2"
        android:name="${applicationName}"
        android:icon="@mipmap/ic_launcher">
        <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>
</manifest>

android/build.gradle

buildscript {
    ext.kotlin_version = '1.7.10'
    repositories {
        google()
        mavenCentral()
        maven {
          url 'https://api.mapbox.com/downloads/v2/releases/maven'
          authentication {
            basic(BasicAuthentication)
          }
          credentials {
            // Do not change the username below.
            // This should always be `mapbox` (not your username).
            username = "mapbox"
            // Use the secret token you stored in gradle.properties as the password
            password = "checked this"
          }
        }
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:7.2.0'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}

allprojects {
    repositories {
        google()
        mavenCentral()
    }
}

rootProject.buildDir = '../build'
subprojects {
    project.buildDir = "${rootProject.buildDir}/${project.name}"
}
subprojects {
    project.evaluationDependsOn(':app')
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

app/build.gradle

def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
    localPropertiesFile.withReader('UTF-8') { reader ->
        localProperties.load(reader)
    }
}

def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
    throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}

def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
    flutterVersionCode = '1'
}

def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
    flutterVersionName = '1.0'
}

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"

android {
    compileSdkVersion flutter.compileSdkVersion
    ndkVersion flutter.ndkVersion

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    kotlinOptions {
        jvmTarget = '1.8'
    }

    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
    }

    defaultConfig {
        // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
        applicationId "com.example.mapbox_try2"
        // You can update the following values to match your application needs.
        // For more information, see: https://docs.flutter.dev/deployment/android#reviewing-the-gradle-build-configuration.
        minSdkVersion 21
        targetSdkVersion flutter.targetSdkVersion
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
    }

    buildTypes {
        release {
            // TODO: Add your own signing config for the release build.
            // Signing with the debug keys for now, so `flutter run --release` works.
            signingConfig signingConfigs.debug
        }
    }
}

flutter {
    source '../..'
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'com.mapbox.maps:android:10.12.1'
 


}

我的代码:

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

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatelessWidget {
  const MyHomePage({super.key});

  @override
  Widget build(BuildContext context) {
    return Container(
      child: MapboxMap(
        accessToken:
            "checked this",
        onMapCreated: (MapboxMapController controller) {
          // Do something when the map is created
        },
        initialCameraPosition: CameraPosition(
          target: LatLng(37.7749, -122.4194),
          zoom: 12,
        ),
      ),
    );
  }
}

我使用了'mapbox_gl:^0.16.0'包以获取它。当我在Vs代码中运行时,它显示任务':app:checkDebugDuplicateClasses执行失败,我尝试使用chatGPT并得到了这个-
app/build.gradle

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'com.mapbox.maps:android:10.12.1'
 
implementation ('com.mapbox.maps:android:10.12.1'){
   configurations {
    all {
        exclude group: 'com.mapbox.mapboxsdk', module: 'mapbox-android-core'
        exclude group: 'com.mapbox.common', module: 'common'
        exclude group: 'com.mapbox.mapboxsdk', module: 'mapbox-sdk-services'
        exclude group: 'com.mapbox.mapboxsdk', module: 'mapbox-sdk-turf'
        exclude group: 'com.mapbox.mapboxsdk', module: 'mapbox-sdk-geojson'
        exclude group: 'com.mapbox.mapboxsdk', module: 'mapbox-sdk-constants'
        exclude group: 'com.mapbox.mapboxsdk', module: 'mapbox-sdk-core'
    }
}
}

}

在此之后,错误消失,并显示白色屏幕0.5秒,然后消失,“正在运行Gradle任务'assembleDebug'...”被卡住/循环,它没有完成或停止。

bvjxkvbb

bvjxkvbb1#

我找到了与multiDexing相关的解决方案。
只需转到应用程序模块build.gradle文件并添加

android {
    defaultConfig {
        ...
        minSdkVersion 21 
        targetSdkVersion flutter.targetSdkVersion
        multiDexEnabled true <-- add this line
    }
    ...
}

在dependencies部分:

dependencies {
    implementation "androidx.multidex:multidex:2.0.1" <-- add this line too
}

这是文档的链接:https://developer.android.com/build/multidex#groovy
希望这能帮上忙。

相关问题