Skip to content

Instantly share code, notes, and snippets.

@chibuezefelix
Last active August 20, 2023 07:02
Show Gist options
  • Select an option

  • Save chibuezefelix/46ae09350cc0101d0abaf36f39b5b8a7 to your computer and use it in GitHub Desktop.

Select an option

Save chibuezefelix/46ae09350cc0101d0abaf36f39b5b8a7 to your computer and use it in GitHub Desktop.
Compose Conditional Modifier extention
fun Modifier.conditional(
condition: Boolean,
ifTrue: Modifier.() -> Modifier,
ifFalse: (Modifier.() -> Modifier)? = null,
): Modifier {
return if (condition) {
then(ifTrue(Modifier))
} else if (ifFalse != null) {
then(ifFalse(Modifier))
} else {
this
}
}
// Null conditoional modifier
fun <T> Modifier.nullConditional(
argument: T?,
ifNotNull: Modifier.(T) -> Modifier,
ifNull: (Modifier.() -> Modifier)? = null,
): Modifier {
return if (argument != null) {
then(ifNotNull(Modifier, argument))
} else if (ifNull != null) {
then(ifNull(Modifier))
} else {
this
}
}
// Usage
@Composable
fun ComplexModifierScene(
nighttime: Boolean,
torchon: Boolean,
modifier: Modifier = Modifier
) {
val backgroundColor = if (nighttime && torchon) {
TorchLight
} else if (!nighttime) {
Sunlight
} else {
Night
}
val boxModifier = modifier
.conditional(nighttime && torchon, {
clip(CircleShape)
})
.fillMaxHeight()
.aspectRatio(1f)
.background(backgroundColor)
.conditional(nighttime && torchon, {
shadow(elevation = 4.dp, shape = CircleShape)
})
.conditional(nighttime && !torchon, {
blur(20.dp)
})
Box(boxModifier) {
Image(painterResource(R.drawable.outline_yard_24), "Scene", Modifier.fillMaxSize())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment