You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 03:54:03