androidandroid-jetpack-composelazycolumn

Avoid verticalArrangement spacing when child item is not added on LazyColumn


Currently, we are developing an app using SDUI. In which, on the parent screen mapper, we are placing Scaffold and LazyColumn. On the child level widget mapper, we are placing the items.

We have conditional item visibility inside the LazyColumn. If the condition doesn't match, we are not showing the item. Because of conditional logic inside LazyColumn and having verticalArrangement this is giving extra gap between next item (as in screenshot).

As a simple demonstration, I have put simple logic below. This is giving extra spacing because of verticalArrangement spacing.

Question: Is there anyway to detect the child item is not added and avoid using vertical spacing? I know we can fix it using spacing on the child level, but we can't do it because of architectural arrangement on the app.

        // Scaffold and LazyColumn are on screen level
        Scaffold {
            LazyColumn(
                modifier = Modifier.padding(it),
                // Can not remove verticalArrangement because of code architectural arrangement
                verticalArrangement = Arrangement.spacedBy(12.dp)
            ) {
                for (i in 1..5) {
                   // item is in widget level
                    item {
                        if (i != 4) {
                            Item("Title: $i")
                        }
                    }
                }
            }
        }

enter image description here


Solution

  • The problem is that you still create an item when you make it invisible. Instead you should remove the item entirely by moving the condition outside the item:

    if (i != 4) {
        item {
            Item("Title: $i")
        }
    }