Home > Back-end >  How to have variant type with more than one passable string in Jetpack Compose
How to have variant type with more than one passable string in Jetpack Compose

Time:10-08

How to have variant type with more than one passable string in Jetpack Compose. If variant is passed from outside it should change the Text color based on the condition. Shows an error if i have two values in variant type - Expecting a top level declaration.

@Composable
fun Label(
    label: String,
    variant: String = "dark" | "light"

) {
        Text(
            text = label,
            fontSize = 24.sp,
//if color = "dark" is passed from outside should change color.
            color = if (variant === "dark") Color.Black else Color.Yellow,
        )
}

CodePudding user response:

You have to hoist your variant state somewhere that uses your Label composable, and have it remember something that the Label can use to update its State , in your case its Color.

Parent Composable that uses Label

 var variant by remember { mutableStateOf("dark") }

 Button(onClick = {
        variant = "light"
 }){
       //Button Label here
 }

 Label(
      label = "Hello World",
      variant = variant
 )

Your Label

@Composable
fun Label(
    label: String,
    variant: String
) {
    Text(
        text = label,
        fontSize = 24.sp,
        color = if (variant === "dark") Color.Black else Color.Yellow,
    ) 
}

CodePudding user response:

If you have only 2 values: dark|light you can use a Boolean instead of a String.

Something like:

@Composable
fun Label(
    label: String,
    variantLight : Boolean =true

) {
    Text(
        text = label,
        fontSize = 24.sp,
        color = if (variantLight) Color.Yellow else Color.Black
    )
}

And then use it with:

var variantLight by remember { mutableStateOf(false) }

Label(
    label = "Hello World",
    variantLight = variantLight
)

If you have more values you can use an enum class:

enum class VariantLabel {
    Light,
    Dark
}

@Composable
fun Label(
    label: String,
    variant: VariantLabel = VariantLabel.Light

) {
    Text(
        text = label,
        fontSize = 24.sp,
        color = if (variant == VariantLabel.Dark) Color.Black else Color.Yellow,
    )
}

and then use it with:

var variantLabel by remember { mutableStateOf(VariantLabel.Light) }

Label(
    label = "Hello World",
    variant = variantLabel
)
  • Related