无法为 org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler 类型的对象设置未知属性“nav_version”

Shr*_*ora 2 java navigation android gradle kotlin

我试图添加导航依赖项以在我的项目中使用导航图,而 android studio 抛出了这个错误。

这是我的项目 Gradle 文件:

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    ext.kotlin_version = '1.3.50'
    repositories {
        google()
        jcenter()
        nav_version = "2.3.0-alpha01" //extra property, used like variables
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.5.3'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files

        classpath "androidx.navigation:navigation-safe-args-gradle-plugin:$nav_version"
    }
}

allprojects {
    repositories {
        google()
        jcenter()

    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
Run Code Online (Sandbox Code Playgroud)

如您所见,我添加了 $nav_version 依赖项和 nav_version 变量。但是,android studio 会抛出“无法为 org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler 类型的对象设置未知属性‘nav_version’”错误。我想知道它是否与 Gradle 版本或我的 Kotlin 版本有关。我试图清理并重新构建我的项目,但没有用。我想知道是否有人遇到过类似的事情。

VVB*_*VVB 5

它应该是应用程序级 build.gradle 的一部分。

就像是

dependencies {
  def nav_version = "2.3.0-alpha01"

  // Kotlin
  implementation "androidx.navigation:navigation-fragment-ktx:$nav_version"
  implementation "androidx.navigation:navigation-ui-ktx:$nav_version"

  // Dynamic Feature Module Support
  implementation "androidx.navigation:navigation-dynamic-features-fragment:$nav_version"

  // Testing Navigation
  androidTestImplementation "androidx.navigation:navigation-testing:$nav_version"
}
Run Code Online (Sandbox Code Playgroud)

和顶级/项目级gradle

buildscript {
    repositories {
        google()
    }
    dependencies {
        def nav_version = "2.3.0-alpha01"
        classpath "androidx.navigation:navigation-safe-args-gradle-plugin:$nav_version"
    }
}
Run Code Online (Sandbox Code Playgroud)

或者像 ${nav_version} 一样放置它

classpath "androidx.navigation:navigation-safe-args-gradle-plugin:${nav_version}"
Run Code Online (Sandbox Code Playgroud)

或者

buildScript {
  ext {
    nav_version = "2.3.0-alpha01"
    kotlin_version = "1.3.50"
  }

    dependencies {
            classpath 'com.android.tools.build:gradle:3.5.3'
            classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:${kotlin_version}"
            // NOTE: Do not place your application dependencies here; they belong
            // in the individual module build.gradle files

            classpath "androidx.navigation:navigation-safe-args-gradle-plugin:${nav_version}"
    }
}
Run Code Online (Sandbox Code Playgroud)

参考 https://developer.android.com/guide/navigation/navigation-getting-started