Is there a way in Flutter to animate the transition when the data of a Text
element changes?
I have a new Text(_value)
element where _value
changes based on a Slider position. Is there any way to animate the transition so it isn't as "aprupt" as it is when just changing _value
?
I know there are widgets to animate the transition between two different widgets, but I'm only changing the data
property of the same Text
widget.
Flutter provides default transition whenever user navigating between the routes. If you think it's kind of boring, don't worry. Flutter lets you to custom the transition flexibly.
Wrap up your text widget with an AnimatedSwitcher widget and inside the transitionBuilder, define your child.
Inside the child(Text widget), define a key like this:
AnimatedSwitcher(
duration: Duration(milliseconds: 200),
transitionBuilder:
(Widget child, Animation<double> animation) {
return SlideTransition(
child: child,
position: Tween<Offset>(
begin: Offset(0.0, -0.5),
end: Offset(0.0, 0.0))
.animate(animation),
);
},
child: Text(
userAnswer,
key: ValueKey<String>(userAnswer),
style: TextStyle(fontSize: 45, color: Colors.white),
),
)
which userAnswer is String.
I needed the same thing so I created a cross_fade
widget.
https://gist.github.com/cirediew/38abb52e27278dae2b8eba77ed4b3bdc
It takes initialData
to display the first time.
data
is your String/double/int/whatever you want to put into your crossfading widget. And the builder
in which you can create your widget.
It is used like this:
CrossFade<String>(
initialData: 'Some String',
data: myString,
builder: (value) => Text(value),
),
Edit:
Null safe version, renamed to AnimatedFadeOutIn
:
https://gist.github.com/cirediew/9f68acb7aed1296a232a5f846071d2c3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With