
CompositionLocal: Sharing Data Across the Compose Tree
CompositionLocal enables efficient, implicit data sharing throughout your Compose hierarchy without prop drilling. Creating a CompositionLocal // Define CompositionLocal val LocalThemeColors = compositionLocalOf { ThemeColors ( primary = Color . Blue , secondary = Color . Green ) } data class ThemeColors ( val primary : Color , val secondary : Color ) // Provide values @Composable fun MyApp () { CompositionLocalProvider ( LocalThemeColors provides ThemeColors ( primary = Color . Red , secondary = Color . Yellow ) ) { MyScreen () } } // Consume values @Composable fun MyButton () { val colors = LocalThemeColors . current Button ( colors = ButtonDefaults . buttonColors ( containerColor = colors . primary ), onClick = {} ) { Text ( "Click" ) } } Static CompositionLocal For values that never change: val LocalUserInfo = staticCompositionLocalOf { UserInfo ( name = "Guest" , id = "0" ) } data class UserInfo ( val name : String , val id : String ) Nested Providers Override values in subtrees:
Continue reading on Dev.to Tutorial
Opens in a new tab




