https://kotlinlang.org logo
#compose-android
Title
# compose-android
d

Dustin

10/04/2023, 1:05 PM
Question about dividers between items
🛟 3
Hi, I often find myself doing something like this
Copy code
Row(){
 if(condition1){
   View1()
 }

  if(condition2){
    View2()
  }

  if(condition3){
    View3()
  }
}
Then if you want to add dividers between each optional view, you need to do something like this
Copy code
Row(){

  if(condition1){
    View1()
  }

  if(condition2){
    if(condition1){
	  Divider()
    }
    View2()
  }

  if(condition3) {
    if(condition1 || condition2){
	  Divider()
    }
    View3()
  }

}
This works it’s just really ugly, anyone have suggestions on making this code nicer
s

Stylianos Gakis

10/04/2023, 1:12 PM
Do you care if the last item also has a divider under it, or do you for sure want them to only be between items?
d

Dustin

10/04/2023, 1:17 PM
only between items
j

jw

10/04/2023, 1:29 PM
maintain a boolean as to whether you need to emit a divider or not before the next item. when you emit an item, reset the boolean value
you could also create lambdas which represent the items, assemble the ones you want to display as a list, and then loop over the list adding a divider before an item if index > 0
⬆️ 1
✔️ 1
2
d

Dustin

10/04/2023, 1:37 PM
so something like this
Copy code
@Composable
fun DividedRow(
    modifier: Modifier = Modifier,
    divider: @Composable () -> Unit,
    vararg items: @Composable() () -> Unit,
) {
    if (items.isEmpty()) {
        return
    }

    Row(modifier = modifier) {
        items.forEachIndexed { index, item ->
            item()
            if (index != items.size - 1) {
                divider()
            }
        }
    }
}
yes thanks, still not that prettiest code but much more scalable
j

jw

10/04/2023, 1:38 PM
You can use
lastIndex
, but it would be better to put the conditional before the item and check
index > 0
because it's faster
2
2 Views