Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter animate transition when Text data changes

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.

like image 387
TommyF Avatar asked Aug 06 '18 11:08

TommyF


People also ask

What is Pageroutebuilder in Flutter?

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.


2 Answers

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.

like image 113
AG80 Avatar answered Sep 23 '22 01:09

AG80


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

like image 41
Er1 Avatar answered Sep 26 '22 01:09

Er1