Search code examples
flutterdarttextwidget

How to animate the color of a text with multiple colors flutter


I want my text to animate through multiple colors in flutter how can I do it.


Solution

  • Pablo's answer (using ColorTween) will animate the color between two values. In order to transition among several colors, you can adapt that solution to either

    • build a "TweenSequence" chaining multiple color tweens
    • use RainbowColor which simplifies transition between multiple colors

    See my article Multicolor Transitions in Flutter for a walkthrough on doing either.

    For reference, here's a multi-color (B->G->R) animated text widget using RainbowColor.

    class ColorText extends StatefulWidget {
      const ColorText({
        Key key,
      }) : super(key: key);
    
      @override
      _ColorTextState createState() => _ColorTextState();
    }
    
    class _ColorTextState extends State<ColorText>
        with SingleTickerProviderStateMixin {
      AnimationController controller;
      Animation<Color> _colorAnim;
    
      @override
      void initState() {
        super.initState();
        controller = AnimationController(duration: Duration(seconds: 3), vsync: this);
        _colorAnim = RainbowColorTween([Colors.blue, 
                                        Colors.green, 
                                        Colors.red, 
                                        Colors.blue])
                .animate(controller)
                  ..addListener(() { setState(() {}); })
                  ..addStatusListener((status) {
                    if (status == AnimationStatus.completed) {
                      controller.reset();
                      controller.forward();
                    } else if (status == AnimationStatus.dismissed) {
                      controller.forward();
                    }
                  });
        controller.forward();
      }
    
      @override
      Widget build(BuildContext context) {
        return Text("Hello!", style: TextStyle(color: _colorAnim.value));
      }
    }