最新消息:XAMPP默认安装之后是很不安全的,我们只需要点击左方菜单的 "安全"选项,按照向导操作即可完成安全设置。

[Flutter]Tween补间动画实践代码大全

XAMPP案例 admin 788浏览 0评论
说明
补间(Tween)动画“介于两者之间”的简称。在补间动画中,定义了开始点和结束点、时间线以及定义转换时间和速度的曲线。然后由框架计算如何从开始点过渡到结束点。IntTween:int 类型的动画

intAnim = IntTween(begin: 0,end: 200).animate(controller)
      ..addListener(() {
      setState(() {
        // the state that has changed here is the animation object’s value
      });
    })..addStatusListener((status){

      });

 

ColorTween:颜色渐变动画

Animation<Color> colorAnim = ColorTween(begin: Colors.grey,end: Colors.red).animate(controller)
      ..addListener(() {
        setState(() {
          // the state that has changed here is the animation object’s value
        });
      })..addStatusListener((status){

      });

 

ReverseTween:反转动画

Animation reverseAnim = ReverseTween(IntTween(begin: 0,end: 200)).animate(controller)
      ..addListener(() {
        print("reverse====${reverseAnim.value}");
        setState(() {
          // the state that has changed here is the animation object’s value
        });
      })..addStatusListener((status){

      });

 

SizeTween:size类型的动画

Animation<Size> sizeAnim = SizeTween(begin: Size(100,100),end: Size(200,200)).animate(controller)
      ..addListener(() {
        print("reverse====${sizeAnim.value}");
        setState(() {
          // the state that has changed here is the animation object’s value
        });
      })..addStatusListener((status){

      });

 

SizedBox.fromSize(
              child: Container(
                color: Colors.red,
              ),
              size: sizeAnim.value,
            )

 

RectTween:Rect 类型动画

rectAnim = RectTween(begin: Rect.fromLTRB(100,100,100,100),end: Rect.fromLTRB(100,100,100,100)).animate(controller)
      ..addListener(() {
        print("reverse====${rectAnim.value}");
        setState(() {
          // the state that has changed here is the animation object’s value
        });
      })..addStatusListener((status){

      });

 

StepTween:步数动画

stepAnim = StepTween(begin: _stepNum,end: 0).animate(controller)
      ..addListener(() {
        print("stepAnim====${stepAnim.value}");
        setState(() {
          this._stepNum = stepAnim.value;
        });
      })..addStatusListener((status){

      });

 

 

ConstantTween:常量值动画

Animation<int> constantAnim = ConstantTween<int>(5).animate(controller)
      ..addListener(() {
        print("stepAnim====${constantAnim.value}");
        setState(() {

        });
      })..addStatusListener((status){

      });

 

主要的类的:

  • Animation 对象,是 Flutter 动画库中的核心类,插入用于引导动画的值。
  • Animation 对象知道当前动画的状态(如:动画是否开始,停止,前进或者后退),但对屏幕上显示的内容一无所知。
  • AnimationController 对象管理着 Animation,默认范围从 0.0 到 1.0。如果需要不同的范围或不同的数据类型,则可以使用 Tween 来配置动画以生成不同的范围或数据类型的值。
  • CurvedAnimation 将动画定义成非线性运动的动画。
  • Tween 是 stateless 的,需要 begin 和 end 值,在被动画对象使用的数据范围之间进行插值。例如,Tween 可能会定义从红色到蓝色或从 0 到 255 的插值。
    final Tween colorTween =
        ColorTween(begin: Colors.transparent, end: Colors.black54);

     

  • 要使用 Tween 对象,调用 animate() 方法,传入一个控制器对象,返回一个 Animation<T>。
    final AnimationController controller = AnimationController(
        duration: const Duration(milliseconds: 500), vsync: this);
    // 在 500 毫秒内生成从 0 到 255 的整数值,返回一个 Animation 对象
    Animation<int> alpha = IntTween(begin: 0, end: 255).animate(controller);

     

 

 

示例一
import 'package:flutter/material.dart';
// 图片宽高匀速从0变到300
class TweenDemo extends StatefulWidget {
  @override
  _ScaleImageState createState() => _ScaleImageState();
}

class _ScaleImageState extends State<TweenDemo> with SingleTickerProviderStateMixin{

  Animation<double> animation;
  AnimationController controller;

  initState() {
    super.initState();
    controller = AnimationController(
        duration: const Duration(seconds: 3), vsync: this);
    //写法1、图片宽高从0变到300
    animation = Tween(begin: 0.0, end: 300.0).animate(controller)
      ..addListener(() {
        setState(()=>{});
      });
    controller.forward();
  }

  @override
  Widget build(BuildContext context) {
    return new Center(
      child: Image.asset("assets/images/2.png",
          width: animation.value,
          height: animation.value
      ),
    );
  }
  @override
  dispose() {
    //路由销毁时需要释放动画资源
    controller.dispose();
    super.dispose();
  }
}

效果:

zzzzzt0063

示例二-ColorTween
import 'package:flutter/material.dart';
//颜色从红到绿
class TweenColorDemo extends StatefulWidget {
  @override
  _ScaleImageState createState() => _ScaleImageState();
}

class _ScaleImageState extends State<TweenColorDemo> with SingleTickerProviderStateMixin{

  Animation<Color> animation;
  AnimationController controller;

  initState() {
    super.initState();
    controller = AnimationController(
        duration: const Duration(seconds: 3), vsync: this);
    //写法1、图片宽高从0变到300
    animation = ColorTween(begin: Colors.green, end: Colors.red).animate(controller)
      ..addListener(() {
        setState(()=>{});
      });
    controller.forward();
  }

  @override
  Widget build(BuildContext context) {
      return Scaffold(
        appBar: AppBar(
          title: Center(child:Text("ColorTween的简单使用")),
          elevation: 0.0,
        ),
        body: Center(
            child:Column(
              children: <Widget>[
                Text("颜色从绿色逐渐变成红色"),
                Container(
                  color: animation.value,
                  width: 50.0,
                  height: 300,
                )
              ],
            )
        )
      );
      /// 从这里可以看出,animation其实和wiget是无关的
  }
  @override
  dispose() {
    //路由销毁时需要释放动画资源
    controller.dispose();
    super.dispose();
  }
}

 

效果:

zzzzzt00063

示例三-ReverseTween
import 'package:flutter/material.dart';
/// 图片宽高匀速从0变到300
class ReverseTweenDemo extends StatefulWidget {
  @override
  _ScaleImageState createState() => _ScaleImageState();
}

class _ScaleImageState extends State<ReverseTweenDemo> with SingleTickerProviderStateMixin{

  Animation<double> animation;
  AnimationController controller;

  initState() {
    super.initState();
    controller = AnimationController(
        duration: const Duration(seconds: 3), vsync: this);

    //写法2 用 ReverseTween
    //必须指定泛型类型
    Tween<double> tween = Tween(begin: 300, end: 0);
    animation = ReverseTween(tween).animate(controller)
      ..addListener(() {
        setState(()=>{});
      });
    controller.forward();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Center(child:Text("ReverseTween的简单使用")),
          elevation: 0.0,
        ),
        body: Center(
          child: Image.asset("assets/images/2.png",
              width: animation.value,
              height: animation.value
          ),
        )
    );
    /// 从这里可以看出,animation其实和wiget是无关的
  }
  @override
  dispose() {
    //路由销毁时需要释放动画资源
    controller.dispose();
    super.dispose();
  }
}

 

效果:

 zzzzzt000063

自定义动画组件
import 'package:flutter/material.dart';

class _AnimatedWidget extends AnimatedWidget {
  //Animation extends Listenable
  _AnimatedWidget({Key key, Animation<double> animation})
      : super(key: key, listenable: animation);

  @override
  Widget build(BuildContext context) {
    final Animation<double> animation = listenable;
    return new Center(
      child: Image.asset("assets/images/1.png",
          width: animation.value, height: animation.value),
    );
  }
}

class AnimatedWidgetDemo extends StatefulWidget {
  @override
  _ScaleAnimationState createState() => _ScaleAnimationState();
}
class _ScaleAnimationState extends State<AnimatedWidgetDemo>
    with SingleTickerProviderStateMixin {
  Animation<double> animation;
  AnimationController controller;

  @override
  void initState() {
    super.initState();
    controller =
        AnimationController(vsync: this, duration: const Duration(seconds: 3));

    animation = Tween(begin: 0.0, end: 300.0).animate(controller)
      ..addStatusListener((status) {
        print("------status==" + status.toString());
        if (status == AnimationStatus.completed) {
          //已经完成
          controller.reverse();
        } else if (status == AnimationStatus.dismissed) {
          //动画的初始状态
          controller.forward();
        }
      });
    controller.forward();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Center(child:Text("AnimatedWidget的简单使用")),
          elevation: 0.0,
        ),
        body:_AnimatedWidget(animation: animation)
    );
    /// 从这里可以看出,animation其实和wiget是无关的
  }

  dispose() {
    //路由销毁时需要释放动画资源
    controller.dispose();
    super.dispose();
  }
}

效果:

zzzzzt0000063

弹簧动画效果
import 'package:flutter/material.dart';

/// 弹簧效果的动画
class CurvedScaleImageDemo extends StatefulWidget {
  @override
  _ScaleImageState createState() => _ScaleImageState();
}

class _ScaleImageState extends State<CurvedScaleImageDemo> with SingleTickerProviderStateMixin{

  Animation<double> animation;
  AnimationController controller;

  initState() {
    super.initState();
    controller = AnimationController(
        duration: const Duration(seconds: 3), vsync: this);
    //使用弹性曲线
    animation =CurvedAnimation(parent: controller, curve: Curves.bounceIn);
    //图片宽高从0变到300
    animation = Tween(begin: 0.0, end: 300.0).animate(animation)
      ..addListener(() {
        setState(()=>{});
      });

    controller.forward();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Center(child:Text("CurvedAnimation的简单使用")),
          elevation: 0.0,
        ),
        body: Center(
          child: Image.asset("assets/images/1.png",
              width: animation.value,
              height: animation.value
          ),
        )
    );
    /// 从这里可以看出,animation其实和wiget是无关的
  }
  @override
  dispose() {
    //路由销毁时需要释放动画资源
    controller.dispose();
    super.dispose();
  }
}

 

效果:

 zzzzzt00000063

示例
import 'package:flutter/material.dart';

class AnimationDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('AnimationDemo'),
          elevation: 0.0,
        ),
        body: AnimationDemoHome());
  }
}

class AnimationDemoHome extends StatefulWidget {
  @override
  _AnimationDemoHomeState createState() => _AnimationDemoHomeState();
}

class _AnimationDemoHomeState extends State<AnimationDemoHome>
    with TickerProviderStateMixin {
  AnimationController animationDemoController;
  Animation animation;
  Animation animationColor;
  CurvedAnimation curve;

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

    animationDemoController = AnimationController(
      // value: 32.0,
      // lowerBound: 32.0,
      // upperBound: 100.0,
      duration: Duration(milliseconds: 1000),
      vsync: this,
    );

    curve = CurvedAnimation(
        parent: animationDemoController, curve: Curves.bounceOut);

    animation = Tween(begin: 32.0, end: 100.0).animate(curve);
    animationColor =
        ColorTween(begin: Colors.red, end: Colors.red[900]).animate(curve);

    // animationDemoController.addListener(() {
    // // print('${animationDemoController.value}');
    // setState(() {});
    // });

    animationDemoController.addStatusListener((AnimationStatus status) {
      print(status);
    });

    // animationDemoController.forward();
  }

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

    animationDemoController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: AnimatedHeart(
        animations: [
          animation,
          animationColor,
        ],
        controller: animationDemoController,
      ),
    );
  }
}

class AnimatedHeart extends AnimatedWidget {
  final List animations;
  final AnimationController controller;

  AnimatedHeart({
    this.animations,
    this.controller,
  }) : super(listenable: controller);

  @override
  Widget build(BuildContext context) {
    return IconButton(
      icon: Icon(Icons.favorite),
      iconSize: animations[0].value,
      color: animations[1].value,
      onPressed: () {
        switch (controller.status) {
          case AnimationStatus.completed:
            controller.reverse();
            break;
          default:
            controller.forward();
        }
      },
    );
  }
}

效果:

zzzzzt000000063

 

示例-StepTween计时器
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
class StepTweenDemo extends StatefulWidget {
  StepTweenDemo({Key key, this.title}) : super(key: key);
  final String title;

  @override
  _StepTweenDemoState createState() => _StepTweenDemoState();
}

class _StepTweenDemoState extends State<StepTweenDemo> with SingleTickerProviderStateMixin{
  AnimationController controller;
  Animation<int> stepAnim;
  int _stepNum = 10;
  @override
  initState() {
    super.initState();
    controller = AnimationController(
        duration: new Duration(seconds: _stepNum), vsync: this);
    controller.addListener((){
      print("controller=====${controller.value}");

    });
    controller.addStatusListener((status){
      print("status====$status");
    });
    stepAnim = StepTween(begin: _stepNum,end: 0).animate(controller)
      ..addListener(() {
        print("stepAnim====${stepAnim.value}");
        setState(() {
          this._stepNum = stepAnim.value;
        });
      })..addStatusListener((status){

      });
    controller.forward();
  }
  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
        appBar: new AppBar(title: const Text('StepTweenDemo')),
        body: Column(
          children: <Widget>[
            new Text(
              stepAnim.value.toString(),
              style: new TextStyle(fontSize: 150.0),
            ),
          ],
        )
    );
  }
  @override
  Ticker createTicker(onTick) {
    return new Ticker(onTick, debugLabel: 'created by $this');
  }
}

效果:

zzzzzt0000000063

转载请注明:XAMPP中文组官网 » [Flutter]Tween补间动画实践代码大全

您必须 登录 才能发表评论!