Junior — Middle
How can components in Compose internally access the current application context?
sobes.tech AI
Answer from AI
In Jetpack Compose, to obtain the current application context within a component, the function LocalContext.current is used. It returns a Context object associated with the current component.
Example:
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.LocalContext
@Composable
fun MyComposable() {
val context = LocalContext.current
// Now you can use context, for example, to access resources
}
This is the preferred way to get the context in Compose, as it considers the lifecycle and ensures proper binding to the current UI.