TommyF
TommyF

Reputation: 7140

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.

Upvotes: 17

Views: 21271

Answers (3)

hasanm08
hasanm08

Reputation: 638

you can use AnimatedCrossFade here is an example:

 AnimatedCrossFade(
                crossFadeState: isSelected
                    ? CrossFadeState.showSecond
                    : CrossFadeState.showFirst,
                duration: const Duration(milliseconds: 400),
                firstChild: Text(
                  title,
                  maxLines: 1,
                  overflow: TextOverflow.clip,
                  style: Theme.of(context)
                      .textTheme
                      .headline5!
                      .copyWith(color: textColor),
                ),
                secondChild: Text(
                  selectedTitle,
                  maxLines: 1,
                  overflow: TextOverflow.clip,
                  style: Theme.of(context).
                         textTheme.
                         headline5!.
                         copyWith(color: selectedColor),
                ),
              ),

Upvotes: 0

Er1
Er1

Reputation: 2758

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

Upvotes: 16

AG_1380
AG_1380

Reputation: 614

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.

Upvotes: 25

Related Questions