Reputation: 97
I want my text to animate through multiple colors in flutter how can I do it.
Upvotes: 3
Views: 10415
Reputation: 358
The example below animate a text color through a Colors range.
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),))));
}
}
Upvotes: 1
Reputation: 787
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
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));
}
}
Upvotes: 4