Question about dividers between items
# compose-android
d
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
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
only between items
j
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
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
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