Home > database >  When should one use Modifier.then?
When should one use Modifier.then?

Time:07-11

What is the purpose or when is it useful to use Modifier.then in jetpack compose?

CodePudding user response:

If you decided some certain properties for a composable but still want to make it customizable you can use then method to take a modifier that you passed as a parameter in your Composable's constructor.

An example :


@ExperimentalComposeUiApi
@Composable
fun CalculatorButton(
    symbol: String,
    modifier: Modifier = Modifier,
    color: Color = Color.White,
    textStyle: TextStyle = TextStyle(),
    onClick: () -> Unit
) {
    Box(
        contentAlignment = Alignment.Center,
        modifier = Modifier
            .clip(RoundedCornerShape(100.dp))
            .background(color)
            .clickable {
                onClick()
            }
            .then(modifier) // <--------- This Line we pass modifier parameter 
                            //            after certain properteis
    ) { //content 
}

CodePudding user response:

You can use it for conditionals, for instance

Modifier. fillMaxWitdh()
    .then(
        if (condition) Modifier.background(color)
        else Modifier.alpha(alpha)
    )
  • Related