Flutter开发 15. 动画的使用
1. AnimationController
AnimationController用于控制动画,它包含动画的启动forward()、停止stop() 、反向播放 reverse()等方法。AnimationController会在动画的每一帧,就会生成一个新的值。默认情况下,AnimationController在给定的时间段内线性的生成从 0.0 到1.0(默认区间)的数字。
默认的构造函数如下:
AnimationController({
double? value,
this.duration,
this.reverseDuration,
this.debugLabel,
this.lowerBound = 0.0,
this.upperBound = 1.0,
this.animationBehavior = AnimationBehavior.normal,
required TickerProvider vsync,
}) : assert(lowerBound != null),
assert(upperBound != null),
assert(upperBound >= lowerBound),
assert(vsync != null),
_direction = _AnimationDirection.forward {
_ticker = vsync.createTicker(_tick);
_internalSetValue(value ?? lowerBound);
}
1.1 常用参数
参数 | 类型 | 说明 |
---|---|---|
duration | Duration? | 动画执行的时长 |
reverseDuration | Duration? | 反向动画执行的时长 |
lowerBound | double | 下边界值,动画执行时可以得到的最小值,也是动画消失时的值 |
upperBound | double | 上边界值,动画执行时可以得到的最大值,也是动画执行完的值 |
vsync | TickerProvider | 它接收一个TickerProvider类型的对象,它的主要职责是创建Ticker用来定时刷新 |
2. 实例演示
2.1 工程文件添加
首选在当前工程下的lib/widgets下添加一个文件 ScanWidget.dart
2.2 创建ScanWidget组件
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
class ScanWidget extends StatefulWidget {
const ScanWidget({Key? key}) : super(key: key);
@override
State<ScanWidget> createState() => _ScanWidgetState();
}
class _ScanWidgetState extends State<ScanWidget>
with SingleTickerProviderStateMixin {
late AnimationController _animationController;
@override
void initState() {
_animationController = AnimationController(
duration: const Duration(seconds: 2),
lowerBound: 10,
upperBound: 11,
vsync: this);
_animationController.forward();
_animationController.addStatusListener((status) {
if (status == AnimationStatus.completed) {
_animationController.reset();
_animationController.forward();
}
});
super.initState();
}
double radius = 50;
@override
Widget build(BuildContext context) {
return Container(
height: radius * 2,
width: radius * 2,
decoration: BoxDecoration(
border: Border.all(
color: const Color.fromARGB(255, 126, 251, 29), width: 1),
borderRadius: BorderRadius.circular(radius),
color: const Color.fromARGB(255, 226, 255, 131),
),
child: Container(
alignment: Alignment.topCenter,
child: RotationTransition(
alignment: Alignment.bottomCenter,
turns: _animationController,
child: Container(
width: 2,
height: radius,
color: const Color.fromARGB(255, 248, 117, 73),
),
),
),
);
}
}
2.3 使用ScanWidget
在Home.dart的build方法中添加使用代码
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("首页"),
),
body: SafeArea(
child: Container(
width: double.infinity,
padding: const EdgeInsets.fromLTRB(0, 30, 0, 0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Text(_strLoginInfo),
ElevatedButton(
onPressed: onClickLogin,
child: const Text("去登录"),
),
const ScanWidget()
]),
),
));
}