Trying to use Font otf file as a FontResource usin...
# multiplatform
n
Trying to use Font otf file as a FontResource using compose1.6.X Getting error like
@Composable invocations can only happen from the context of a @Composable function
Can anyone please help me or share doc from where i can get idea to fix this ? Reference taken from : https://www.jetbrains.com/help/kotlin-multiplatform-dev/compose-images-resources.html#fonts Thanks
b
I haven't implemented it with the new 1.6 way, but that shows it needing to be called from a composable. You could either create the font in a composable function and access it elsewhere or set it up at the top level as a compositionLocal
Copy code
val LocalFont = compositionLocalOf<FontFamily?> {null}
Copy code
@Composable
fun MainView() {
    val fontFamily = FontFamily(Font(Res.font.yourfont, weight = FontWeight.Bold))

    CompositionLocalProvider(
        LocalFont provides fontFamily
    ) {
        Text("hello", fontFamily = LocalFont.currentOrThrow)
    }
You could also just make a composable function that returns it
Copy code
@Composable
fun someFont(): FontFamily { 
    return FontFamily(Font(Res.font.yourfont, weight = FontWeight.Bold))
}
Copy code
Text(text = "hello", fontFamily = someFont())
You could maybe apply it to the material theme typography as well if it's an app wide thing, that's created in a composable as well
Copy code
MaterialTheme(
     typography = Typography(defaultFontFamily = FontFamily(Font(Res.font.yourfont)))
 ) {
     Text(text = "hello", style = MaterialTheme.typography.body1, fontWeight = FontWeight.Bold)
 }