在使用动画的时候,一般会这样写
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,
),
),
],
),
),
);
}
}