Issue
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,
)
}
Solution
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
)
Answered By - Gabriele Mariotti
Answer Checked By - Willingham (JavaFixing Volunteer)