https://kotlinlang.org logo
#compose
Title
# compose
r

Roberto Leinardi

05/13/2022, 11:20 AM
I'm making a Composable that should show a list of other Composables, visually something like this, but I'm not sure how to request for these Composables as parameter. Since I'm showing them inside a Column I first thought to do just ask for a list of
actions: @Composable ColumnScope.() -> Unit
but I have now realized that I need to iterate to each Composable to animate it properly (see here). Is there a way to iterate over the
actions: @Composable ColumnScope.() -> Unit
? Or should I ask for a
actions: List<@Composable () -> Unit> = emptyList()
? Or is there a better way to achieve what I need to do?
1
s

ste

05/13/2022, 12:01 PM
Hmm, not sure if it really fits your use case, but you could create you own
*Scope
class, e.g.
Copy code
@Composable
fun MyThing(content: @Composable MyThingScope.() -> Unit) {
    Column {
        MyThingScope(this).content()
    }
}

class MyThingScope(columnScope: ColumnScope) : ColumnScope by columnScope {
    @Composable
    fun MyThingItem(content: @Composable () -> Unit) {
        // now you can access every item separately
    }
}
E.g.:
Copy code
@Composable
fun MyThing(content: @Composable MyThingScope.() -> Unit) {
    val counterState = remember {
        mutableStateOf(0)
    }

    Column(
        horizontalAlignment = Alignment.End,
        modifier = Modifier
            .animateContentSize()
    ) {
        remember {
            MyThingScope(counterState, this)
        }.content()
    }
}

class MyThingScope(counterState: MutableState<Int>, columnScope: ColumnScope) : ColumnScope by columnScope {
    private var counter by counterState

    @Composable
    fun MyThingItem(content: @Composable () -> Unit) {
        val isVisible by produceState(false) {
            delay(counter++ * 100L)
            value = true
        }

        AnimatedVisibility(visible = isVisible) {
            content()
        }
    }
}
(however, you also have the requirement to draw elements from bottom to top, and there's no such feature in a
Column
, so you probably need a custom layout for that - otherwise you could ask for the number of items to display, and then calculate a reversed delay to make the first item appear last)
r

Roberto Leinardi

05/13/2022, 12:49 PM
Hey thanks, yeah I was looking at the implementation of the LazyColumn and saw that they are using a Scope for the items. I'm now playing with this, thanks again!
2 Views