如何为Kotlin桌面Compose演示项目启用@Preview?

6
我下载了 演示项目 来学习 Kotlin Compose。
我尝试在 @Composable 函数上添加 @Preview,但是收到警告:未解决的引用:Preview 我在 build.gradlw.kts 中的 kotlin.sourceSets.named("CommonMain").dependencies 添加了 implementation("androidx.compose.ui:ui-tooling-preview:1.1.1")
        named("commonMain") {
            dependencies {
                api(compose.runtime)
                api(compose.foundation)
                api(compose.material)
                api(compose.materialIconsExtended)
                implementation("androidx.compose.ui:ui-tooling-preview:1.1.1")
            }
        }

但仍然出现未解决的引用:Preview错误。

我使用的是 IDEA 2021.3.3,Build #IU-213.7172.25,构建于2022年3月16日。


你是否已经导入了注释 import androidx.compose.ui.tooling.preview.Preview?另外,你尝试过使用Android Studio吗?根据文档,预览仅在AS中工作。 - Sergei Kozelko
3个回答

26

你需要导入 androidx.compose.desktop.ui.tooling.preview.Preview 在桌面端预览。

前往 设置 > 插件 > 市场搜索 Compose Multiplatform IDE Support 并安装该插件。

之后,你可以使用 Preview 注解,并且它会自动导入正确的库。


2
这个答案应该被接受为正确的。 - CodeAlo

7
首先,我们需要明白我们正在将我们的组合或视图创建到共享模块的commonMain中。因此,我们无法告诉IDE我们需要预览的平台。这应该是你的文件夹结构。
|- sharedModule
    |- androidMain
    |- desktopMain
    |- commonMain
        |- composables

然后我们需要按照以下步骤为每个平台创建预览。
  1. 为每个要预览的sourceSet添加UI预览工具依赖。
val compose_version = "1.4.1"

val commonMain by getting {
    dependencies {
        // we don't need add anything in here
    }
}

val desktopMain by getting {
    dependencies {
        implementation("org.jetbrains.compose.ui:ui-tooling-preview:${compose_version}")
    }
}

val androidMain by getting {
    dependencies {
        implementation("org.jetbrains.compose.ui:ui-tooling-preview:${compose_version}")
    }
}

将您的预览添加到特定的sourceSet模块中。
我们假设我们有一个名为MyComposable的视图。
现在,我们需要在所需的预览sourceSet平台模块中创建我们的预览。
如果需要,我们还可以添加桌面预览。
您的文件应该如下所示。
希望对您有所帮助。

这应该是我个人认为应该被接受的答案。正如你所说,重要的是,你不要把你的预览放在commonMain目录中,而是放在androidMain目录中。 - undefined

0
请记住,@Preview函数不能带任何参数。
@Preview
@Composable
fun testingPreview() {
    MaterialTheme {
        Text(text = "Test")
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接