flutter中 AnimationController的vsync: this报错

在使用动画的时候,一般会这样写

  AnimationController _controller;
  Animation<double> _animation;
  Animation<Offset> _offsetAnimation;


  @override
  void initState() {
    super.initState();
    _controller =
    AnimationController(vsync: this, duration: Duration(seconds: 2))
      ..repeat(reverse: true);
    _animation = CurvedAnimation(parent: _controller, curve: Curves.easeIn);
    _offsetAnimation = Tween<Offset>(begin: Offset.zero, end: Offset(1.5, 0.0))
        .animate(_controller);
  }

但是AnimationController中的vsync: this,会报错(存在vsync时会防止屏幕外动画(动画的 UI不在当前屏幕时)消耗不必要的资源。)

这里我们需通过将SingleTickerProviderStateMixin添加到类定义中,可以将statefulWidget类对象作为vsync中this的值。如果要使用自定义的State对象作为vsync时,也可使用TickerProviderStateMixin

写法一

class DemoSizeTransition extends StatefulWidget {
  @override
  _DemoSizeTransitionState createState() => _DemoSizeTransitionState();
}

class _DemoSizeTransitionState extends State<DemoSizeTransition>
{
	with SingleTickerProviderStateMixin {
	.....//放你的这个状态类的内容
	}
}

写法二

import 'package:flutter/material.dart';
///代码清单
class DemoSizeTransition extends StatefulWidget {
  @override
  _DemoSizeTransitionState createState() => _DemoSizeTransitionState();
}

class _DemoSizeTransitionState extends State<DemoSizeTransition> with SingleTickerProviderStateMixin
{

  AnimationController _controller;
  Animation<double> _animation;
  Animation<Offset> _offsetAnimation;


  @override
  void initState() {
    super.initState();
    _controller =
    AnimationController(vsync: this, duration: Duration(seconds: 2))
      ..repeat(reverse: true);
    _animation = CurvedAnimation(parent: _controller, curve: Curves.easeIn);
    _offsetAnimation = Tween<Offset>(begin: Offset.zero, end: Offset(1.5, 0.0))
        .animate(_controller);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: [
            FadeTransition(
              opacity: _animation,
              child: FlutterLogo(
                size: 150,
              ),
            ),
            SlideTransition(
              position: _offsetAnimation,
              child: FlutterLogo(
                size: 150,
              ),
            ),
          ],
        ),
      ),
    );
  }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值