You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Compose Desktop的Composable中获取build.gradle.kts的packageVersion?

在Compose Desktop中获取nativeDistributions里的packageVersion值

有两种常用方式可以在Composable组件中获取nativeDistributions里配置的packageVersion:

方式一:通过BuildConfig生成编译期常量

这种方法借助第三方插件生成常量,直接在代码中引用,简单高效。

  1. 先在build.gradle.kts中引入BuildConfig插件,并配置版本常量:
plugins {
    kotlin("jvm")
    id("org.jetbrains.compose")
    // 引入BuildConfig插件(版本可根据需求调整)
    id("com.github.gmazzo.buildconfig") version "3.1.0"
}

buildConfig {
    // 从nativeDistributions中读取版本号,生成BuildConfig常量
    val appVersion = compose.desktop.application.nativeDistributions.packageVersion
    buildConfigField("String", "APP_VERSION", "\"$appVersion\"")
}

// 保留原有compose.desktop配置
compose.desktop {
    application {
        mainClass = "com.helper.MainKt"    
        nativeDistributions {
            targetFormats(TargetFormat.Exe)
            packageName = "Helper"
            packageVersion = "1.0.0"
        }
    }
}
  1. 在Composable组件中直接引用生成的常量:
@Composable
fun VersionInfo() {
    Text(text = "应用版本:${BuildConfig.APP_VERSION}")
}

方式二:生成资源文件并读取(无需第三方插件)

如果不想引入额外插件,可以通过生成资源文件的方式传递版本号。

  1. 在build.gradle.kts中添加任务,将版本号写入version.properties资源文件:
// 生成版本信息资源文件的任务
tasks.register("generateVersionProps") {
    val outputFile = file("src/main/resources/version.properties")
    doLast {
        val appVersion = compose.desktop.application.nativeDistributions.packageVersion
        outputFile.writeText("app.version=$appVersion")
    }
}

// 让编译任务依赖该生成任务,确保资源文件提前生成
tasks.compileKotlin.dependsOn("generateVersionProps")
  1. 在Composable组件中读取资源文件:
@Composable
fun VersionInfo() {
    val version = remember {
        runCatching {
            javaClass.classLoader.getResourceAsStream("version.properties")?.use { stream ->
                val props = java.util.Properties()
                props.load(stream)
                props.getProperty("app.version", "未知版本")
            }
        }.getOrDefault("未知版本")
    }
    Text(text = "应用版本:$version")
}

两种方式各有优劣:方式一编译时生成常量,性能更好;方式二无需额外依赖,更轻量化,可根据项目需求选择。

内容的提问来源于stack exchange,提问作者NullPointerException

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 21:34:51