Hi Friends Greetings of the day Is there a way fo...
# compose-android
s
Hi Friends Greetings of the day Is there a way for us to use AnimatedVisibility using a nullable state? For example, this code only works for enter animations but not exit:
Copy code
@Composable
fun MyTextField(errorMessage: (@Composable () -> Unit)? = null) {
  var value by remember { mutableStateOf("") }
  Column {
    TextField(value = value, onValueChanged = { value = it })

    // Here, the enter animation works as expected, but as soon as `errorMessage`
    // becomes null, the `errorMessage` composable just snaps away instead of 
    // gracefully going out.
    AnimatedVisibility(errorMessage != null) {
      errorMessage?.invoke()
    }
  }
}
s
The issue here lays in
errorMessage?.invoke()
. As soon as your error message goes null, there is no longer any content to display inside of your AnimatedVisibility block. The AnimatedVisibility is correctly animating and playing the exit, but the content inside of it snaps to nothing.
🙌 1
🙌🏼 1
To solve this, you should respond to
errorMessage == null
by showing a cache of what the message was before it became null
g
I usually solve this by using
Crossfade
which doesn't have this problem (it composes each input individually)
s
Understood, thanks Seri!
b
Should also be able to use AnimatedContent with
errorMessage
as the targetState
s
Should also be able to use AnimatedContent with
errorMessage
as the targetState
Doesn't work unfortunately :(( I tried both AnimatedContent and AnimatedVisibility Seri's
cache
point makes sense, I was hoping compose would do it out of the box (like Flutter does) but maybe this is something I ought to take care of in Compose.
b
add a Spacer for the else when errorMessage is null
i
AnimatedContent is indeed exactly what you want - it already stores a cache of the state - just make sure you are using that cache by using the value passed into your lambda and not your state object from outside the AnimatedContent
thank you color 1
1
s
Am I missing something here @Ian Lake?
i
You're capturing a lambda which is presumably always getting the latest state when it is invoked, you need to actually pass in the exact state you want to capture into the AnimatedContent
s
Okay, so instead of accepting a nullable lambda, it's better to accept a nullable String in this particular case? Because passing
String?
instead of
(@Composable () -> Unit)?
doesn't help either. It produces the same animation effect. Only one of the animations work (either enter or exit, never both). By any chance, do you have any example that has already implemented something like this?