是否有可能在CompositionLocalProvider中获得上下文?



我有一些配置在json文件中存储在应用程序的资产文件夹。我需要这个配置在我的整个应用程序,所以我认为一个CompositionLocalProvider可能是一个很好的选择。

但是现在我意识到我需要上下文来解析json文件,而这似乎是不可能的。

可能有另一种方法来实现我正在寻找的目标吗?

这是我目前为止的实现:

val LocalAppConfiguration = compositionLocalOf {
Configuration.init(LocalContext.current) // <-- not possible
}

我的配置如下:

object Configuration {
lateinit var branding: Branding
fun init(context: Context) {
val gson = GsonBuilder().create()
branding = gson.fromJson(
InputStreamReader(context.assets.open("branding.json")),
Branding::class.java
)
}
}

如果有人能进一步帮助我,我将非常感激

compositionLocalOf不是Composable函数。因此,LocalContext.current不能使用。

我相信如果您将branding的初始化移出默认工厂,您可以实现类似的目标。然后,您可以在您可以访问Context的实际组合中进行初始化。

下面是一个示例代码来解释我所说的内容。

val LocalAppConfiguration = compositionLocalOf {
Configuration
}
@Composable
fun RootApp(
isDarkTheme: Boolean = isSystemInDarkTheme(),
content: @Composable () -> Unit
) {
val brandedConfiguration = Configuration.init(LocalContext.current)
MaterialTheme {
CompositionLocalProvider(LocalAppConfiguration provides brandedConfiguration) {
//your app screen composable here.
}
}
}

请注意,您还必须稍微修改您的init方法。

object Configuration {
lateinit var branding: Branding
fun init(context: Context) : Configuration {
val gson = GsonBuilder().create()
branding = gson.fromJson(
InputStreamReader(context.assets.open("branding.json")),
Branding::class.java
)
return this
}
}

相关内容

最新更新