Flutter如何实现末尾增速放缓的数字递增动画效果
Flutter 分段缓动数字递增动画实现方案
核心思路
- 总动画时长为两段耗时之和
3s,通过TweenSequence定义两段数值变化区间,通过 weight 属性分配各段的时长占比,完美匹配需求的分段耗时规则 - 配合
AnimationController驱动动画,AnimatedBuilder监听动画值更新实时刷新数字展示
完整实现代码
import 'package:flutter/material.dart'; class CountUpAnimationPage extends StatefulWidget { const CountUpAnimationPage({super.key}); @override State<CountUpAnimationPage> createState() => _CountUpAnimationPageState(); } class _CountUpAnimationPageState extends State<CountUpAnimationPage> with SingleTickerProviderStateMixin { late AnimationController _controller; late Animation<double> _countAnimation; @override void initState() { super.initState(); // 总时长3秒 = 1s + 2s _controller = AnimationController(vsync: this, duration: const Duration(seconds: 3)); // 定义分段动画 _countAnimation = TweenSequence([ // 0→90 段:权重1,占总时长1/3=1秒 TweenSequenceItem( tween: Tween<double>(begin: 0, end: 90), weight: 1, ), // 90→100 段:权重2,占总时长2/3=2秒,加减速曲线让末尾速度更慢 TweenSequenceItem( tween: Tween<double>(begin: 90, end: 100).chain(CurveTween(curve: Curves.decelerate)), weight: 2, ), ]).animate(_controller); // 启动动画 _controller.forward(); } @override void dispose() { _controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( body: Center( child: AnimatedBuilder( animation: _countAnimation, builder: (context, child) { // 转成整数展示,需要小数/特殊格式可修改此处处理逻辑 final showCount = _countAnimation.value.toInt(); return Text( "$showCount", style: const TextStyle(fontSize: 48, fontWeight: FontWeight.bold), ); }, ), ), ); } }
扩展说明
- 如果需要在动画结束后触发回调,可以给
_controller添加StatusListener,监听AnimationStatus.completed状态即可 - 如果要调整数值的展示格式(比如保留小数、添加千分符),直接修改
AnimatedBuilder中对_countAnimation.value的处理逻辑即可
内容的提问来源于stack exchange,提问作者Yusuf Güzel
相关产品推荐
相关产品推荐

