在移动应用开发中,流畅的动画不仅可以给人留下美好的印象,还可以提高用户体验。在Flutter开发中,官方提供了简洁且强大的动画API,比较核心的有AnimationController和Animation。

下面是使用AnimationController和Animation实现一个简单的数字增长动画,效果如下图所示。

Flutter 数字增加动画_flutter


下面是源码:

import 'package:flutter/material.dart';
import 'package:gc_data_app/utils/utils.dart';

class AnimText extends StatefulWidget {

final int number;
final int duration;
final Color fontColor;
final double fontSize;

const AnimText({
Key key,
this.number,
this.duration,
this.fontColor,
this.fontSize,
}) : super(key: key);

@override
State<StatefulWidget> createState() {
return AnimState();
}
}

class AnimState extends State<AnimText> with SingleTickerProviderStateMixin {

AnimationController controller;
Animation animation;
var begin=0;

@override
void initState() {
super.initState();
controller = AnimationController(
vsync: this, duration: Duration(milliseconds: widget.duration));
final Animation curve=CurvedAnimation(parent: controller,curve: Curves.linear);
animation = IntTween(begin: begin, end: widget.number).animate(curve)..addStatusListener((status) {
if(status==AnimationStatus.completed){
// controller.reverse();
}
});
}

@override
Widget build(BuildContext context) {
controller.forward();
return AnimatedBuilder(
animation: controller,
builder: (context,child){
return Container(
child:Text(animation.value,
style: TextStyle(fontSize: widget.fontSize, color: widget.fontColor,fontWeight: FontWeight.bold)),
);
} ,
);
}

@override
void dispose() {
controller.dispose();
super.dispose();
}
}

使用时,只需要按照构造函数的要求传递对应的参数即可。