68

I am trying to create a Column in Jetpack Compose with a specific amount of spacing between each child element, such as 10.dp. In SwiftUI, this is relatively simple. I would just create a VStack with a spacing value:

struct ContentView: View {
    let strings = ["Hello", "World", "Apples"]

    var body: some View {
        VStack(spacing: 10) {
            ForEach(strings, id: \.self) { string in
                Text(string).background(Color.green)
            }
        }
        .background(Color.blue)
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

This is what it looks like in a SwiftUI Preview:

enter image description here

In Jetpack Compose, my code is:

@Composable
fun ContentView() {
    val strings = listOf<String>("Hello", "World", "Apples")

    MaterialTheme {
        Surface(color = MaterialTheme.colors.background) {
            Column(
                modifier = Modifier
                    .background(Color.Blue)
                    // I would expect to be able to add something like ".spacer(10.dp)" here
            ) {
                strings.forEach { string ->
                    Text(
                        modifier = Modifier.background(Color.Green),
                        text = string
                    )
                }
            }
        }
    }
}

@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
    ContentView()
}

Because this code is missing any spacing, this is what it currently looks like:

enter image description here

My criteria are:

  • A space of a specific height (such as 10.dp) should be present between child elements of a Column.
  • The space should not appear before the first element.
  • The space should not appear after the last element.

I would use a Spacer element, but I don't believe this would work, because in a for loop, I believe I would end up having a Spacer either before the first or after the last element, which I do not want.

Eugene
  • 3,417
  • 5
  • 25
  • 49
  • 6
    You're looking for the [`verticalArrangement`](https://developer.android.com/reference/kotlin/androidx/compose/foundation/layout/package-summary#Column(androidx.compose.ui.Modifier,androidx.compose.foundation.layout.Arrangement.Vertical,androidx.compose.ui.Alignment.Horizontal,kotlin.Function1)) parameter. You can pass in something like `Arrangement.spacedBy(10.dp)`. It's also possible to write your own custom `Arrangement` if you need something the system doesn't provide for you. – adneal Jun 30 '21 at 19:30
  • Yes, that's exactly what I'm looking for, thank you @adneal! – Eugene Jun 30 '21 at 23:58

1 Answers1

184

Use Arrangement.spacedBy

Column(
    modifier = Modifier
        .background(Color.Blue),
    verticalArrangement = Arrangement.spacedBy(10.dp)
) {
    // content here
}

enter image description here

Francesc
  • 25,014
  • 10
  • 66
  • 84