天天看點

Flutter 數字增加動畫

在移動應用開發中,流暢的動畫不僅可以給人留下美好的印象,還可以提高使用者體驗。在Flutter開發中,官方提供了簡潔且強大的動畫API,比較核心的有AnimationController和Animation。

下面是使用AnimationController和Animation實作一個簡單的數字增長動畫,效果如下圖所示。

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