Issue
Material-UI offers a nice way to style its components for React. where you define the style in a different place then the component. For everybody who has never heard of this this looks like this
const useStyles = makeStyles({
root: {
background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)',
border: 0,
borderRadius: 3,
boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .3)',
color: 'white',
height: 48,
padding: '0 30px',
},
});
export default function Hook() {
const classes = useStyles();
return <Button className={classes.root}>Hook</Button>;
}
Here you define the root
object as the style for the button
and pass it as a single parameter. This looks so clean and makes the code so much more readable because it separates ui and logic, which gets mixed quiet a lot in compose in my mind.
Is there any way or workaround to have a similar behaviour in Jetpack compose with Kotlin. I thought of a data class that can be destructured or a wrapper function around each object that passes the styling.
Solution
In Compose you can't create styles like this, instead you can create composables with applied styling, and then reuse it in your app. I applied some of your example styles so you should get the idea:
@Composable
fun RootButton(
onClick: () -> Unit,
modifier: Modifier = Modifier,
enabled: Boolean = true,
content: @Composable RowScope.() -> Unit
) {
Surface(
contentColor = Color.White.copy(alpha = 1f),
onClick = onClick,
enabled = enabled,
role = Role.Button,
interactionSource = MutableInteractionSource(),
indication = rememberRipple(),
color = Color.Transparent,
modifier = modifier
.background(
brush = Brush.linearGradient(
colors = listOf(
Color.Red,
Color.Yellow
)
),
shape = RoundedCornerShape(3.dp),
)
) {
ProvideTextStyle(
value = MaterialTheme.typography.button
) {
Row(
Modifier
.defaultMinSize(
minWidth = ButtonDefaults.MinWidth,
minHeight = ButtonDefaults.MinHeight
)
.padding(ButtonDefaults.ContentPadding),
horizontalArrangement = Arrangement.Center,
verticalAlignment = Alignment.CenterVertically,
content = content
)
}
}
}
Then anywhere in your app:
RootButton(onClick = {}) {
Text("Hello")
}
Answered By - Philip Dukhov
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.