在Flutter中,动画组件主要由AnimationController、CurvedAnimation、Tween、AnimatedBuilder等组成。
- Animation
- Animation是抽象类,和UI渲染没有关系,功能是保存动画的插值和状态;比较常用的是Animation
- addListener:帧监听器中最常见的行为是改变状态后调用setState()来触发UI重建
- addStatusListener:动画开始、结束、正向或反向(见AnimationStatus定义)时会调用状态改变的监听器。
- Curve
- 动画过程可以是匀速的、匀加速的或者先加速后减速等。Flutter中通过Curve(曲线)来描述动画过程,我们把匀速动画称为线性的(Curves.linear),而非匀速动画称为非线性的。
Curves曲线 动画过程
linear 匀速的
decelerate 匀减速
ease 开始加速,后面减速
easeIn 开始慢,后面快
easeOut 开始快,后面慢
easeInOut 开始慢,然后加速,最后再减速
以下是一个简单的示例,展示如何使用AnimationController创建一个简单的淡入淡出动画:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: HomePage(),
);
}
}
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> with TickerProviderStateMixin {
AnimationController controller;
CurvedAnimation curve;
@override
void initState() {
super.initState();
controller = AnimationController(
duration: const Duration(milliseconds: 2000),
vsync: this,
);
curve = CurvedAnimation(
parent: controller,
curve: Curves.easeInOut,
);
}
@override
void dispose() {
controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: AnimatedBuilder(
animation: curve,
builder: (BuildContext context, Widget child) {
return Container(
color: Colors.deepOrange,
width: 100.0 + 200.0 * curve.value,
height: 100.0 + 200.0 * curve.value,
);
},
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
if (controller.isDismissed) {
controller.forward();
} else if (controller.isCompleted) {
controller.reverse();
}
},
child: Icon(Icons.play_arrow),
),
);
}
}