android-jetpack-compose

Understanding CompositionLocal


Docs

// MyActivity.kt file

class MyActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContent {
            // Calculate elevations based on the system theme
            val elevations = if (isSystemInDarkTheme()) {
                Elevations(card = 1.dp, default = 1.dp)
            } else {
                Elevations(card = 0.dp, default = 0.dp)
            }

            // Bind elevation as the value for LocalElevations
            CompositionLocalProvider(LocalElevations provides elevations) {
                // ... Content goes here ...
                // This part of Composition will see the `elevations` instance
                // when accessing LocalElevations.current
            }
        }
    }
}

In CompositionLocalProvider when they say 'Content goes here' what kind of content is it suppose to be / can be ?

I'm just looking for global variables and it's all very going around with Compose.


Solution

  • For global variables in Compose:

    Example of Global State:

    val LocalUserName = compositionLocalOf { "Default User" }
    
    @Composable
    fun MyApp() {
        CompositionLocalProvider(LocalUserName provides "Local") {
            Greeting()
        }
    }
    
    @Composable
    fun Greeting() {
        Text("Hello, ${LocalUserName.current}!")
    }
    

    This pattern lets you manage global-like values cleanly and in a Compose idiomatic way, without directly relying on traditional global variables