如何为具有多种颜色波动的文本设置动画颜色

时间:2020-05-04 19:53:03

标签: flutter dart text widget

我希望我的文字通过多种颜色动画显示,该如何处理。

2 个答案:

答案 0 :(得分:1)

下面的示例通过“颜色”范围为文本颜色设置动画。

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  MyAppState createState() {
    return MyAppState();
  }
}

class MyAppState extends State<MyApp> with SingleTickerProviderStateMixin{
  AnimationController controller;
  Animation animation;
  Color color;

  @override
  @mustCallSuper
  void initState() {
    super.initState();
    controller=AnimationController(
      vsync: this,
      duration: Duration(seconds: 5)
    );
    animation=ColorTween(begin:Colors.red,end: Colors.white).animate(controller);

    animation.addListener((){
      setState(() {
        color=animation.value;
      });
    });

    controller.forward();
  }

  @override
  Widget build(BuildContext context) {

    return MaterialApp(home:Scaffold(

        appBar: AppBar(title: Text("Example")),
        body:Center(child:Text("HELLO!!!",textScaleFactor:3,style: TextStyle(color: color),))));
  }
}

答案 1 :(得分:1)

Pablo的答案(使用ColorTween)将对两个值之间的颜色进行动画处理。为了在几种颜色之间转换,您可以使该解决方案适应其中任何一种

  • 构建一个“ TweenSequence”链接多个补间色
  • 使用RainbowColor可以简化多种颜色之间的过渡

有关执行上述任一操作的演练,请参见我的文章Multicolor Transitions in Flutter

作为参考,这是一个使用RainbowColor的多色(B-> G-> R)动画文本小部件。

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));
  }
}