I'm trying to use compose resources files in my co...
# compose
e
I'm trying to use compose resources files in my commonMain. If add a drawable I can render it perfectly in my compose preview via
painterResource(Res.drawable.test)
. Now if I do
Res.getUri("files/test.txt")
or
Res.readBytes("files/test.txt")
I'm getting this error:
Copy code
java.lang.IllegalStateException: Android context is not initialized. If it happens in the Preview mode then call PreviewContextConfigurationEffect() function.
Is it a limitation from compose resources, no file loading from common code?
m
See https://kotlinlang.org/docs/multiplatform/compose-multiplatform-resources-usage.html#raw-files You have to put files that you want to read that way into the files folder (or sub-folder).
e
Edited my message, my file is in `files`:
This is the code I have, in `commonMain`:
Copy code
@OptIn(ExperimentalResourceApi::class)
@Preview
@Composable
fun MyPreview() {
    Column(modifier = Modifier.fillMaxWidth()) {
        val resourceReader = LocalResourceReader.current
        val bytes = remember {
            runBlocking {
                resourceReader.read("files/test.txt")
                // Will throw java.lang.IllegalStateException: Android context is not initialized. If it
                // happens in the Preview mode then call PreviewContextConfigurationEffect() function.
            }
        }
        Image(
            // Works fine, resource load so somehow file is able to load. painterResource also uses LocalResourceReader?
            painter = painterResource(Res.drawable.test),
            contentDescription = "",
        )
    }
}
m
Have you called PreviewContextConfigurationEffect() somewhere? There is an issue dealing with this: https://youtrack.jetbrains.com/projects/CMP/issues/CMP-4338/Ability-to-use-Compose-Multiplatform-resources-in-Preview
e
PreviewContextConfigurationEffect()
isn't available in
commonMain
? Only in
androidMain
.
I tried the hack on the linked ticket ☝🏻 ... while it work with hardcoded path it's not really practical, I can't find away to get the absolute path from the preview runtime.
120 Views