kotlinandroid-studioandroid-jetpack-compose

How to Fix FlowRow Items to Follow Start While Maintaining Equal Space Between Them?


"I tried switching to Arrangement.Start, and it works, but it does not maintain equal spacing between the other items."

FlowRow(
           modifier = Modifier
               .fillMaxWidth(),
           verticalArrangement = Arrangement.spacedBy(8.dp),
           horizontalArrangement = Arrangement.SpaceBetween, // Start alignment for boxes

       ) {
           // Create 8 square boxes
           repeat(8) {
               Box(
                   modifier = Modifier
                       .size(120.dp) // Adjust size for square boxes
                       .background(Color.Blue) // Change color as needed

               )
           }
       }

enter image description here


Solution

  • What you are trying to achieve is not possible with the native FlowRow, as it is not possible to specify an individual horizontalArrangement only for the last row. You only could achieve it by workarounds.

    As you are trying to build a grid, I would suggest to use a LazyVerticalGrid instead which already brings all functionality that you are trying to implement:

    LazyVerticalGrid(
        columns = GridCells.Adaptive(120.dp),
        verticalArrangement = Arrangement.spacedBy(8.dp),
        horizontalArrangement = Arrangement.spacedBy(8.dp)
    ) {
        items(8) {
            Box(
                modifier = Modifier
                    .size(120.dp) // if you adjust size, also adjust GridCells.Adaptive 
                    .background(Color.Blue)
            )
        }
    }
    

    It will give you equal spacing, arrangement from the start, and will dynamically display more columns if enough screen space is available. Additionally, it will lay out its items lazily, meaning that you will have no performance problems when you display a lot of items.

    Output:

    Screenshot