Make the content composable dynamically with slot Api
Mozhdeh Nouri Sarani
Android Developer : Kotlin | Mentor | Technical Knowledge Sharing | Team Player
As you know composable functions can include calls to one or more other composable functions. This usually means that the content of a composable is predefined in terms of which other composables it calls and, therefore, the content it displays.
For Instance:
@Composable
fun GeneralDialogContent(
title: String,
description: String,
yesAction: () -> Unit,
noAction: () -> Unit
){
Column {
Text(text = title)
Spacer(modifier = Modifier.weight(1f))
Text(text = description)
Row {
Button(onClick = {
yesAction()
}) {
Text(text = "yes")
}
Button(onClick = {
noAction()
}) {
Text(text = "no")
}
}
}
}
In the above example, we can see static Impelemnetion of Dialog Content Now consider what happens if we have a case that we should only show one button What should we do?
Slot Api
It can be helpful to think of a slot API composable as a user interface template in which one or more elements are left blank.
Consider the implementation Column internally
@Composable
inline fun Column(
modifier: Modifier = Modifier,
verticalArrangement: Arrangement.Vertical = Arrangement.Top,
horizontalAlignment: Alignment.Horizontal = Alignment.Start,
content: @Composable ColumnScope.() -> Unit)
content uses a Slot API because we have much different implementation in Column
Now continue our previous example the Dialog
Because we are not sure about the implementation of buttons in Dialog and we have several button implementations with different labels we use slot API
@Composable
fun GeneralDialogContent(
title: String,
description: String,
actionContent : @Composable () ->Unit
){
Column {
Text(text = title)
Spacer(modifier = Modifier.weight(1f))
Text(text = description)
actionContent()
}
}
Every time you call content dialog it has a different implementation
@Composable
fun SenarioNumberOne(){
GeneralDialogContent(title= "Delete",
description= "Are you sure?" ){
Row {
Button(onClick = {
// implement delete action
}) {
Text(text = "delete")
}
Button(onClick = {
// implement cancel action
}) {
Text(text = "cancel")
}
}
}
@Composable
fun SenarioNumberTwo(){
GeneralDialogContent(title= "Exit",
description = "Your phone is unsecured you must exit the app ")
{
Button(onClick = {
// implement exit action
}) {
Text(text = "exit")
}
}
}