Junior — Middle
How is the mechanism of using modifiers for public functions implemented in Jetpack Compose?
sobes.tech AI
Answer from AI
In Jetpack Compose, modifiers (Modifier) are used to change the appearance and behavior of UI components. For public functions that create or return a Composable, it is common to add a parameter modifier: Modifier = Modifier with a default value. This allows the calling code to pass a chain of modifiers for customizing the component.
Example:
@Composable
fun MyButton(
text: String,
modifier: Modifier = Modifier
) {
Button(
onClick = { /* action */ },
modifier = modifier
) {
Text(text)
}
}
Thus, the caller can use:
MyButton("Press me", modifier = Modifier.padding(16.dp).fillMaxWidth())
This provides flexibility and reusability of components, allowing easy combination of styles and behaviors through modifiers.