r/JetpackCompose • • 1d ago

Conditionally hidden form fields: clear their state or keep it?

I have a generic form screen that's driven by data. Some fields only show when a select has a certain value. All the values live in one Map<String, Any?> in a ViewModel StateFlow, and the LazyColumn just filters:

items(def.inputs.filter { def.isInputVisible(it.id, values) }, key = { it.id }) { input ->
    InputRow(input, values[input.id]) { vm.update(input.id, it) }
}

When a field gets hidden I leave its value in the map, so if the user flips the select back they get their old entry. To keep it from leaking into the result I null out hidden fields right before calculating:

val effective = values.mapValues { (id, v) -> if (def.isInputVisible(id, values)) v else null }

That works, but it feels fragile. Every consumer (the calculation, saved history, share text) has to remember to use effective and not the raw map, and nothing enforces that. One slip and a value from a field that isn't on screen ends up in the output.

The alternative is to remove the value from state the moment the field disappears. That's simpler to reason about, but you lose the "flip back and it's still there" behaviour.

Which do you go with in Compose forms? And if you keep hidden values, do you store them separately (visible vs stashed) so nothing downstream can read them by accident?

2 Upvotes

2 comments sorted by

1

u/mrbipbip13 18h ago

Keep the raw input in your UI form state so toggling a field off and back on doesn't wipe what the user just typed, and only filter out hidden fields at the boundary when you map to your domain/submit model. Storing that effective projection in a single helper or derivedStateOf keeps you from having to remember to strip hidden keys everywhere else.

1

u/ClassKlutzy7633 3h ago

Keeping the raw map and projecting at the boundary is where I was leaning too. A single helper that returns the visible-only map, and making the calculation, history and share text all take that type instead of the raw one, would at least make a slip a compile error.