E/GlanceAppWidget:Glance App Widget 错误 IllegalStateException:CompositionLocal LocalConfiguration 不存在

E/GlanceAppWidget: Error in Glance App Widget IllegalStateException: CompositionLocal LocalConfiguration not present

我正在使用 Compose 开发应用小部件。我在从资源中获取字符串时遇到问题。如果我将文本作为 text = "Label" 之类的字符串提供,它可以正常工作。但是,如果我使用 stringResource 提供,则不会显示文本,并且我看到了这个问题。有没有人遇到过这个问题?谢谢

E/GlanceAppWidget: Error in Glance App Widget
    java.lang.IllegalStateException: CompositionLocal LocalConfiguration not present
        at androidx.compose.ui.platform.AndroidCompositionLocals_androidKt.noLocalProvidedFor(AndroidCompositionLocals.android.kt:167)
        at androidx.compose.ui.platform.AndroidCompositionLocals_androidKt.access$noLocalProvidedFor(AndroidCompositionLocals.android.kt:1)
        at androidx.compose.ui.platform.AndroidCompositionLocals_androidKt$LocalConfiguration.invoke(AndroidCompositionLocals.android.kt:47)
        at androidx.compose.ui.platform.AndroidCompositionLocals_androidKt$LocalConfiguration.invoke(AndroidCompositionLocals.android.kt:44)
        at kotlin.SynchronizedLazyImpl.getValue(LazyJVM.kt:74)
        at androidx.compose.runtime.LazyValueHolder.getCurrent(ValueHolders.kt:29)
        at androidx.compose.runtime.LazyValueHolder.getValue(ValueHolders.kt:31)
        at androidx.compose.runtime.ComposerImpl.resolveCompositionLocal(Composer.kt:1776)
        at androidx.compose.runtime.ComposerImpl.consume(Composer.kt:1746)
        at androidx.compose.ui.res.StringResources_androidKt.resources(StringResources.android.kt:78)
        at androidx.compose.ui.res.StringResources_androidKt.stringResource(StringResources.android.kt:36)
class MarketWidget : GlanceAppWidget() {

    @Composable
    override fun Content() {
        Column(
            modifier = GlanceModifier
                .fillMaxSize()
                .background(color = Color.White)
                .padding(8.dp)
        ) {
            Text(
                text = stringResource(id = R.string.app_name)
            )
        }
    }
}

stringResource 是 Compose UI 的一部分,因此您不能在 Glance 中使用它。 Glance 的文本只接受已解析的字符串,您可以使用 LocalContext.current.

检索它

要更改您的示例,这应该可行:

Text(text = LocalContext.current.getString(R.string.app_name))

此外,确保您导入的是 Glance Text (androidx.glance.text.Text) 而不是 Material Compose UI (androidx.compose.material.Text)