使用flutter_local_notifications和位置包的flutter错误“Android依赖'androidx.core:core'有不同的版本”

Posted

技术标签:

【中文标题】使用flutter_local_notifications和位置包的flutter错误“Android依赖\'androidx.core:core\'有不同的版本”【英文标题】:flutter Error "Android dependency 'androidx.core:core' has different version" using flutter_local_notifications and location packages使用flutter_local_notifications和位置包的flutter错误“Android依赖'androidx.core:core'有不同的版本” 【发布时间】:2019-07-16 07:28:56 【问题描述】:

美好的一天,我尝试为 androidios 制作一个带有通知的简单天气应用程序,为此我使用基本的 Flutter 应用程序和库 flutter_local_notifications: ^0.5.1+2location: ^2.0.0,但同时使用它们时出现错误:

Launching lib\main.dart on SM A520F in debug mode...
Initializing gradle...
Resolving dependencies...
Gradle task 'assembleDebug'...

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:preDebugBuild'.
> Android dependency 'androidx.core:core' has different version for the compile (1.0.0-rc01) and runtime (1.0.1) classpath. You should manually set the same version via DependencyResolution

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 2s
Finished with error: Gradle task assembleDebug failed with exit code 1

颤振医生输出:

C:\src\flutter\bin\flutter.bat doctor --verbose
[√] Flutter (Channel stable, v1.0.0, on Microsoft Windows [Version 10.0.17134.590], locale ru-RU)
    • Flutter version 1.0.0 at C:\src\flutter
    • Framework revision 5391447fae (3 months ago), 2018-11-29 19:41:26 -0800
    • Engine revision 7375a0f414
    • Dart version 2.1.0 (build 2.1.0-dev.9.4 f9ebf21297)

[√] Android toolchain - develop for Android devices (Android SDK 28.0.3)
    • Android SDK at C:\Users\zande\AppData\Local\Android\sdk
    • Android NDK location not configured (optional; useful for native profiling support)
    • Platform android-28, build-tools 28.0.3
    • Java binary at: C:\Program Files\Android\Android Studio\jre\bin\java
    • Java version OpenJDK Runtime Environment (build 1.8.0_152-release-1248-b01)
    • All Android licenses accepted.

[√] Android Studio (version 3.3)
    • Android Studio at C:\Program Files\Android\Android Studio
    • Flutter plugin version 32.0.1
    • Dart plugin version 182.5124
    • Java version OpenJDK Runtime Environment (build 1.8.0_152-release-1248-b01)

[!] VS Code (version 1.31.0)
    • VS Code at C:\Users\zande\AppData\Local\Programs\Microsoft VS Code
    • Flutter extension not installed; install from
      https://marketplace.visualstudio.com/items?itemName=Dart-Code.flutter

[√] Connected device (1 available)
    • SM A520F • 5200291746c1b485 • android-arm64 • Android 8.0.0 (API 26) (emulator)

! Doctor found issues in 1 category.
Process finished with exit code 0

我的 pubspec.yaml:

name: flutter_app
description: A new Flutter application.

# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# Read more about versioning at semver.org.
version: 1.0.0+1

environment:
  sdk: ">=2.0.0-dev.68.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^0.1.2
  flutter_local_notifications: ^0.5.1+2
  location: ^2.0.0

dev_dependencies:
  flutter_test:
    sdk: flutter


# For information on the generic Dart part of this file, see the
# following page: https://www.dartlang.org/tools/pub/pubspec

# The following section is specific to Flutter.
flutter:

  # The following line ensures that the Material Icons font is
  # included with your application, so that you can use the icons in
  # the material Icons class.
  uses-material-design: true

  # To add assets to your application, add an assets section, like this:
  # assets:
  #  - images/a_dot_burr.jpeg
  #  - images/a_dot_ham.jpeg

  # An image asset can refer to one or more resolution-specific "variants", see
  # https://flutter.io/assets-and-images/#resolution-aware.

  # For details regarding adding assets from package dependencies, see
  # https://flutter.io/assets-and-images/#from-packages

  # To add custom fonts to your application, add a fonts section here,
  # in this "flutter" section. Each entry in this list should have a
  # "family" key with the font family name, and a "fonts" key with a
  # list giving the asset and other descriptors for the font. For
  # example:
  # fonts:
  #   - family: Schyler
  #     fonts:
  #       - asset: fonts/Schyler-Regular.ttf
  #       - asset: fonts/Schyler-Italic.ttf
  #         style: italic
  #   - family: Trajan Pro
  #     fonts:
  #       - asset: fonts/TrajanPro.ttf
  #       - asset: fonts/TrajanPro_Bold.ttf
  #         weight: 700
  #
  # For details regarding fonts from package dependencies,
  # see https://flutter.io/custom-fonts/#from-packages

我的 main.dart:

import 'dart:async';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:location/location.dart';

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

class MyApp extends StatelessWidget 
  // 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: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  


class MyHomePage extends StatefulWidget 
  MyHomePage(Key key, this.title) : super(key: key);

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();


class _MyHomePageState extends State<MyHomePage> 
  int _counter = 0;

  void _incrementCounter() 
    setState(() 
      // This call to setState tells the Flutter framework that something has
      // changed in this State, which causes it to rerun the build method below
      // so that the display can reflect the updated values. If we changed
      // _counter without calling setState(), then the build method would not be
      // called again, and so nothing would appear to happen.
      _counter++;
    );
  

  @override
  Widget build(BuildContext context) 
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    return Scaffold(
      appBar: AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
      ),
      body: Center(
        // Center is a layout widget. It takes a single child and positions it
        // in the middle of the parent.
        child: Column(
          // Column is also layout widget. It takes a list of children and
          // arranges them vertically. By default, it sizes itself to fit its
          // children horizontally, and tries to be as tall as its parent.
          //
          // Invoke "debug painting" (press "p" in the console, choose the
          // "Toggle Debug Paint" action from the Flutter Inspector in Android
          // Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
          // to see the wireframe for each widget.
          //
          // Column has various properties to control how it sizes itself and
          // how it positions its children. Here we use mainAxisAlignment to
          // center the children vertically; the main axis here is the vertical
          // axis because Columns are vertical (the cross axis would be
          // horizontal).
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.display1,
            ),
            RaisedButton(
                onPressed: () 
                  setState(() 
                    _counter = 0;
                  );
                ,
                child: Text('to 0')),
            new Padding(
              padding: new EdgeInsets.fromLTRB(0.0, 0.0, 0.0, 8.0),
              child: new Text(
                  'Tap on a notification when it appears to trigger navigation'),
            ),

          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  

  Future onSelectNotification(String payload) async 
    showDialog(
      context: context,
      builder: (_) 
        return new AlertDialog(
          title: Text("PayLoad"),
          content: Text("Payload : $payload"),
        );
      ,
    );
  

我的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 from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"

android 
    compileSdkVersion 28

    lintOptions 
        disable 'InvalidPackage'
    

    defaultConfig 
        // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
        applicationId "com.example.flutterapp"
        minSdkVersion 16
        targetSdkVersion 28
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    

    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 
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'


我尝试使用其他地理定位库,但经常遇到类似的错误

D8: Program type already present: android.support.v4.os.ResultReceiver$MyResultReceiver

对于geo_location_finder 库

WARNING: This version of device_info will break your Android build if it or its dependencies aren't compatible with AndroidX.

对于geolocator 库

我应该怎么做才能制作我的天气应用程序?

【问题讨论】:

首先,迁移到AndroidX 如何制作? 我将android.useAndroidX=trueandroid.enableJetifier=true 添加到grandle.properities。该项目仍然使用每个库单独构建,但两者都会产生一个新错误: Execution failed for task ':app:preDebugBuild'. &gt; Android dependency 'androidx.versionedparcelable:versionedparcelable' has different version for the compile (1.0.0-rc01) and runtime (1.0.0) classpath. You should manually set the same version via DependencyResolution 迁移到 AndroidX 最简单的方法是打开 Android 项目并使用 Refactor 菜单。此外,您的问题可能是因为您的插件使用 AndroidX,而其他插件没有,在这种情况下,您必须分叉有问题的插件并修复它以使其使用 AndroidX 【参考方案1】:

不开玩笑,我最近遇到了同样的问题(我收到了很多关于 AndroidX 的各种依赖项的投诉,以 -rc01 版本结尾),并且用于强制解决策略的各种解决方案都不起作用。

我通过在 android/build.gradle 文件中升级我的 gradle 依赖项解决了这个问题:classpath 'com.android.tools.build:gradle:3.3.1'(我之前使用的是 3.2.1 版)

【讨论】:

【参考方案2】:

我遇到了来自 androidX 兼容性的相同问题。错误消息如下所示:

android dependency 'androidx.core:core' has different version for the compile (1.0.0) and runtime (1.0.1) classpath

我修复如下(如果相同,忽略它):

    android/gradle/wrapper/gradle-wrapper.properties 中更改以 distributionUrl 开头的行,如下所示:

distributionUrl=https://services.gradle.org/distributions/gradle-4.10.2-all.zip

    android/build.gradle

依赖 类路径 'com.android.tools.build:gradle:3.3.0'

buildscript 下(如果它包括 kotlin)

ext.kotlin_version = '1.3.0'

    android/gradle.properties 中,追加

android.enableJetifier=true

android.useAndroidX=true

    android/app/build.gradle

在 android 下,确保 compileSdkVersion 和 targetSdkVersion 至少为 28。

...

testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"

依赖项下

androidTestImplementation 'androidx.test:runner:1.1.1'

androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'

实现'com.android.support:multidex:1.0.3'

默认配置下

multiDexEnabled 真

希望这会有所帮助!!!

【讨论】:

这很有帮助。正如 Prakhar 在另一个答案中所说,com.android.tools.build:gradle:3.3.1 版本可能是解决方案的关键。

以上是关于使用flutter_local_notifications和位置包的flutter错误“Android依赖'androidx.core:core'有不同的版本”的主要内容,如果未能解决你的问题,请参考以下文章

在使用加载数据流步骤的猪中,使用(使用 PigStorage)和不使用它有啥区别?

今目标使用教程 今目标任务使用篇

Qt静态编译时使用OpenSSL有三种方式(不使用,动态使用,静态使用,默认是动态使用)

MySQL db 在按日期排序时使用“使用位置;使用临时;使用文件排序”

使用“使用严格”作为“使用强”的备份

Kettle java脚本组件的使用说明(简单使用升级使用)