FlowLayout - devrath/ComposeAlchemy GitHub Wiki

Usage

  • We can use the flow layout to scenarios where the items(views) cannot fill the width of the row/column
  • They will be pushed to the next row/column if the space is unavailable for a view to be placed.
  • The layout handles automatically of placing the items automatically depending on the space available

How is the FlowLayout different compared to LazyList

  • In the flow layout all the items are drawn at a time.
  • In the lazy list only the visible items are drawn and as we keep scrolling the other items are drawn lazily one after the other.

Code

@OptIn(ExperimentalLayoutApi::class)
@Composable
fun FlowLayoutDemoScreen(modifier: Modifier = Modifier) {

    var isExpanded by remember { mutableStateOf(false) } // State to track expansion

    val items = (1..40).toList() // Sample data

    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(16.dp),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center,
    ) {

        FlowRow(
            modifier = Modifier
                .fillMaxWidth()
                .padding(8.dp),
            horizontalArrangement = Arrangement.spacedBy(12.dp),
            verticalArrangement = Arrangement.spacedBy(8.dp),
            maxItemsInEachRow = Int.MAX_VALUE
        ) {

            // Show only the first few items when collapsed, show all when expanded
            val visibleItems = if (isExpanded) items else items.take(10)
            val expandedItemsIndicator = if (isExpanded) Icons.Default.KeyboardArrowUp else Icons.Default.KeyboardArrowDown
            val description = if (isExpanded) "Collapse" else "Expand"
            
            // Render visible items
            visibleItems.forEach { item ->
                AssistChip(
                    onClick = {},
                    label = { Text("Item-$item") }
                )
            }

            // Expand/Collapse Indicator
            if (items.size > 10) {
                IconButton(
                    onClick = { isExpanded = !isExpanded } // Toggle expand/collapse
                ) {
                    Icon(
                        imageVector = expandedItemsIndicator,
                        contentDescription = description
                    )
                }
            }
        }
    }

}

Output

demo.webm