我正在尝试使用安全参数,但是当我将依赖项添加到项目级别 build.gradle 时,它​​给了我这个错误

srd*_*aa7 7 android kotlin build.gradle

plugins {
   id 'com.android.application' version '7.2.1' apply false
   id 'com.android.library' version '7.2.1' apply false
   id 'org.jetbrains.kotlin.android' version '1.7.10' apply false
}
dependencies {
   "android.arch.navigation:navigation-safe-args-gradle-plugin:$version_navigation"
}

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

原因:groovy.lang.MissingPropertyException:无法获取 org.gradle.api.internal.artifacts.dsl.dependency.DefaultDependencyHandler 类型的对象的未知属性“version_navigation”。

Tha*_*oro 33

dependencies您不能在from项目模块根目录中使用该块。正确的方法是添加块及其内部,如下所示:build.gradlebuildscriptdependencies

buildscript {
    dependencies {
        classpath 'androidx.navigation:navigation-safe-args-gradle-plugin:2.5.3'
    }
}

plugins {
    id 'com.android.application' version '7.4.1' apply false
    id 'com.android.library' version '7.4.1' apply false
    id 'org.jetbrains.kotlin.android' version '1.8.10' apply false
}
Run Code Online (Sandbox Code Playgroud)

请记住,您还可以选择遵循新的结构模式,并且不使用块dependency,您可以使用plugins块:

plugins {
    id 'com.android.application' version '7.4.1' apply false
    id 'com.android.library' version '7.4.1' apply false
    id 'org.jetbrains.kotlin.android' version '1.8.10' apply false
    id 'androidx.navigation.safeargs' version '2.5.3' apply false
}
Run Code Online (Sandbox Code Playgroud)

build.gradlefrom app 模块中,它保持不变。

plugins {
    // ...
    id 'androidx.navigation.safeargs.kotlin'
}
Run Code Online (Sandbox Code Playgroud)

您必须确保库的依赖项遵循相同的版本以避免出现问题。
当您需要多个gradle文件中的版本时,为了方便这一版本控制,您还可以在from项目模块ext中包含一个带有版本的块,并使用它代替gradle文件中的版本号。完整示例:buildscriptbuild.gradle

build.gradle(项目)

buildscript {
    ext {
        navigation_ver = '2.5.3'
    }

    // if you want the 'old' way:
    // dependencies {
        // classpath "androidx.navigation:navigation-safe-args-gradle-plugin:$navigation_ver"
    // }
}

plugins {
    id 'com.android.application' version '7.4.1' apply false
    id 'com.android.library' version '7.4.1' apply false
    id 'org.jetbrains.kotlin.android' version '1.8.10' apply false
    // if you want the 'new' way:
    id 'androidx.navigation.safeargs' version "$navigation_ver" apply false
}
Run Code Online (Sandbox Code Playgroud)

build.gradle(应用程序模块)

plugins {
    id 'com.android.application'
    id 'org.jetbrains.kotlin.android'
    id 'androidx.navigation.safeargs.kotlin'
}

android {
    // ...
}

dependencies {
    // ...
    implementation "androidx.navigation:navigation-ui-ktx:$navigation_ver"
    implementation "androidx.navigation:navigation-fragment-ktx:$navigation_ver"
}
Run Code Online (Sandbox Code Playgroud)