What is the proper way of showing/hiding a composa...
# compose
m
What is the proper way of showing/hiding a composable, but keeping its space so the layout doesn’t change? Currently, as the composable is selectable, i am using .alpa(if(show 1f else 0f) which works, but i feel there must be a better way
manager to implement this solution
Copy code
fun Modifier.visibility(visible: Boolean) = this.then(
    Modifier.layout { measurable, constraints ->
        val placeable = measurable.measure(constraints)
        layout(placeable.width, placeable.height) {
            if (visible) {
                placeable.place(0, 0)
            }
        }
    }
)
it will keep the space, but skip the layout phase. it seems to work
v
Seems to me like this would be a good feature request.
c
I think I saw a feature request for this already? I believe in there the recommended way was just to flip alpha back and forth so you can hide something while still taking up space.
a
v
That seems overly confusing, couldn't one do something to be more inline with what they are used to and make a function work similar to hidden and gone? And just have that function flip the alpha?
To me that would be more of what people would be expecting
c
The Android view system had visible, invisible/hidden and gone. It's just not something compose supports out of the box. Compose is still new so there's definitely stuff missing, but if you wanted this functionality you could write your own modifier that just changed the alpha. It's probably what the compose teams version would do if they implement it.
a
In a declarative UI framework gone is not needed. You just remove the declaration.
☝️ 1
l
Sometimes gone is needed; keeping the state but removing from layout.
v
Ahh I know. The answer is Viewmodel to keep state.
a
Not necessarily view model. You can also use
remember { SomeState() }
.
v
True, I wonder which would be better? Or would it depend on if you are already using a viewmodel? I guess technically using remember in your parent's composable would be easiest to implement and control whether or not to add view to the composition.
a
Depends on whether the state is a pure UI state. For example I wouldn't put a
LazyListState
into the view model.
z
I think not placing the element is probably closer to what you need than just setting alpha. If you place it with zero alpha, everything like input handlers, semantics, etc will stay there. If you don't place it at all, they won't be.
d
There are still valid usecases. The one I've had just yesterday: there's a text field and an error text under it. it spans several lines depending on localization. I want to show or hide the error and I don't want this to cause a field to jump vertically.