首页 > 建站教程 > APP开发,混合APP >  Flutter笔记71:数字变化的补间动画IntTween简单案例正文

Flutter笔记71:数字变化的补间动画IntTween简单案例

Flutter数字变化的补间动画IntTween,可以给数字变化加上补间动画,Flutter其实提供了一种数字文字变化的动画组件:AnimatedSwitcher切换时的动画组件,动画效果很不错。

number.dart:
import 'package:flutter/material.dart';

class NumberAnimation extends StatefulWidget{
  NumberAnimation({Key key}) : super(key:key);

  _NumberAnimationState createState() => _NumberAnimationState();
}

//混入 SingleTickerProviderStateMixin 是为了在不显示当前页面时,动画停止,节约资源
class _NumberAnimationState extends State<NumberAnimation> with SingleTickerProviderStateMixin{
  AnimationController _controller;
  Animation animation;

  @override
  void initState() {
    super.initState();

    _controller = AnimationController(duration:Duration(seconds: 1), vsync: this);

    //自定义非线性动画
    final Animation curve = CurvedAnimation(parent: _controller, curve: Curves.easeOut);

    animation = IntTween(begin: 0,end: 10).animate(curve)..addStatusListener((status) {
      //判断动画完成
      if(status == AnimationStatus.completed){
        //反转动画
        _controller.reverse();
      }
      //判断动画执行到开始的地方
      if(status == AnimationStatus.dismissed){
        Navigator.pop(context);
      }
    });
  }

  //销毁动画
  @override
  void dispose() {
    super.dispose();
    _controller.dispose();
  }

  @override
  Widget build(BuildContext context) {
    //执行动画
    _controller.forward();

    return AnimatedBuilder(
      animation: _controller,
      builder: (context,child){
        return Scaffold(
          appBar: AppBar(
            title: Text('数字动画'),
          ),
          body: Center(
            child: Text(
              animation.value.toString(),
              style: TextStyle(fontSize: 48.0),
            ),
          ),
        );
      }
    );
  }
}
main.dart:
import 'package:flutter/material.dart';
import 'number.dart';

void main(){
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      child: MaterialApp(
        title: 'Flutter边框补间动画BorderRadiusTween实现遮罩动画',
        theme: ThemeData(
          primarySwatch: Colors.blue
        ),
        debugShowCheckedModeBanner: false,
        home: AnimateDemo(),
      ),
    );
  }
}

class AnimateDemo extends StatelessWidget{
  @override
  Widget build(BuildContext context) {

    List<Widget> list = [
      NumberAnimation()
    ];

    return Scaffold(
      appBar: AppBar(
        title: Text('动画示例'),
      ),
      body: ListView(
        children: list.map((widget){
          return ListTile(
            title: Text(widget.toString()),
            onTap: (){
              Navigator.of(context).push(MaterialPageRoute(builder: (context)=>widget));
            },
          );
        }).toList(),
      ),
    );
  }
}