在Android中,我们可以用XML来指定动画样式,或者调用View的animate()
方法。在Flutter中,widget的动画效果利用animated
动画化组件的动画库来实现。
Flutter中,使用AnimationController
来控制动画暂停、调整进度、停止和倒退。AnimationController
继承自Animation<double>
。
在vsync信号发出时,需要一个触发器来通知它,从而在每帧中产生一个0到1的线性差值。
一个Controller可以与多个动画进行关联。
当整个屏幕刷新完毕,即一个垂直刷新周期完成,会有短暂的空白期,此时发出 VSync 信号。
动画样式示例 - CurvedAnimation与FadeTransition
用CurvedAnimation
实现一个动画效果。
给widget指定动画效果,用Controller来控制动画的播放。
下面这个例子是关于FadeTransition的。用一个FloatingActionButton来控制动画播放。
import 'package:flutter/material.dart';
void main() => runApp(new AnimationApp());
class AnimationApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Animation',
theme: new ThemeData(primarySwatch: Colors.blue),
home: new HomePage(
title: '动画示例',
),
);
}
}
class HomePage extends StatefulWidget {
final String title;
HomePage({Key key, this.title}) : super(key: key);
@override
State<StatefulWidget> createState() => new _HomePageState();
}
// 需要Ticker
class _HomePageState extends State<HomePage> with TickerProviderStateMixin {
AnimationController controller;
CurvedAnimation curveEaseIn, bounceIn, linear, decelerate;
bool _animationFlag = true;
@override
void initState() {
super.initState();
controller = new AnimationController(
duration: new Duration(milliseconds: 2000), vsync: this);
curveEaseIn = new CurvedAnimation(parent: controller, curve: Curves.easeIn);
bounceIn = new CurvedAnimation(parent: controller, curve: Curves.bounceIn);
linear = new CurvedAnimation(parent: controller, curve: Curves.linear);
decelerate =
new CurvedAnimation(parent: controller, curve: Curves.decelerate);
}
@override
Widget build(BuildContext context) {
buildItemWidget(
CurvedAnimation animation, MaterialColor color, String itemText) {
return new Column(
children: <Widget>[
new FadeTransition(
opacity: animation,
child: new FlutterLogo(
size: 100.0,
colors: color,
),
),
new Text(itemText)
],
);
}
return new Scaffold(
appBar: new AppBar(
title: new Text(widget.title),
),
floatingActionButton: new FloatingActionButton(
onPressed: () {
if (_animationFlag) {
controller.forward();
} else {
controller.reverse();
}
_animationFlag = !_animationFlag;
},
child: new Icon(Icons.star),
),
body: new Center(
child: new GridView.extent(
maxCrossAxisExtent: 170.0,
padding: const EdgeInsets.all(12.0),
children: <Widget>[
buildItemWidget(curveEaseIn, Colors.blue, 'Curves.easeIn'),
buildItemWidget(bounceIn, Colors.amber, 'Curves.bounceIn'),
buildItemWidget(linear, Colors.red, 'Curves.linear'),
buildItemWidget(decelerate, Colors.indigo, 'Curves.decelerate'),
buildItemWidget(
new CurvedAnimation(
parent: controller, curve: Curves.elasticIn),
Colors.pink,
'Curves.elasticIn'),
buildItemWidget(
new CurvedAnimation(parent: controller, curve: Curves.ease),
Colors.purple,
'Curves.ease'),
],
),
),
);
}
}
效果图1
网友评论