How to handle missing CompositionLocal value?

Viewed 29

How can I handle the case where a CompositionLocal object is not available to a composable? I can't use try catch as "Try catch is not supported around composable function invocations."

Consider the following code:

// LocalElevations.kt file
data class Elevations(val card: Dp = 0.dp, val default: Dp = 0.dp)

// Define a CompositionLocal global object with a default
// This instance can be accessed by all composables in the app
val LocalElevations = compositionLocalOf { Elevations() }

// Somewhere else, try to access the current value of LocalElevations
val elevations: Elevations

// ISSUE HERE: Compiler complains: "Try catch is not supported around composable function invocations."
try { 
   elevations = LocalElevations.current
} catch (e: IllegalStateException) {
    // use default values etc.
}
1 Answers

You can do something different.
You can provide a default value in your theme.

Something like:

val elevations = Elevations()
MaterialTheme(
       colors = colors,
       typography = Typography,
       shapes = Shapes
){
    CompositionLocalProvider( LocalElevations provides elevations ) {
        content()
    }
}

In this way the default value is always provided and you can get it with

val currentElevations = LocalElevations.current

and you can override it using something like:

val newElevations = Elevations(card = 2.dp)
CompositionLocalProvider( LocalElevations provides newElevations ) {
    //your content
}
Related