碰到的问题

最近在搞Flutter,碰到了一个动画需求,【点击按钮组件从左边滑出,再次点击后从左边消失】

使用了SizeTransition组件+AnimationController实现动画的播放和控制

动画代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// 动画控制器
AnimationController(
vsync: this,
duration: const Duration(milliseconds: 800), // 动画时长
..repeat(); // 动画循环
)
...
// 动画组件
SizeTransition(
sizeFactor: _animationController, // 动画控制器
axis: Axis.horizontal, // 动画方向
axisAlignment: 0.0, // 基础位移
child: const Text("动画"),
),

如果不希望动画一直循环,在动画控制器一定不要加上..repeat()

加上按钮控制动画播放

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// 定义一个变量记录动画目前的状态
_animationIsPlayer = false;

...
// 按钮控制动画
IconButton(
splashColor: Colors.transparent,
highlightColor: Colors.transparent,
hoverColor: Colors.transparent,
onPressed: () {
setState(() {
_animationIsPlayer = !_animationIsPlayer;
if (_isShowPlayer) {
// 播放 from 表示起点
_animationController.forward(from: 0);
} else {
// 倒放 from 表示起点
_animationController.reverse(from: 1);
}
});
},
icon: const Icon(IconFontIcons.iconRight)
),

完整代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
// 【重要】你的组件一定要混入 SingleTickerProviderStateMixin 类
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key});
@override
State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage>
with SingleTickerProviderStateMixin {

late AnimationController _animationController;
_animationIsPlayer = false;

@override
void initState() {
// 创建动画控制器
_animationController = AnimationController(
vsync: this,
duration: const Duration(milliseconds: 800), // 动画时长
reverseDuration: const Duration(milliseconds: 600) // 反向动画时长
)
}

// 页面销毁时
@override
void dispose() {
// 销毁动画控制器
_animationController.dispose();
super.dispose();
}

@override
Widget build(BuildContext context) {
return Row(
children: [
// 动画
SizeTransition(
sizeFactor: _animationController, // 动画控制器
axis: Axis.horizontal, // 动画方向
axisAlignment: 0.0, // 基础位移
child: const Text("动画"),
),
// 按钮控制动画
SizedBox(
height: 80,
width: 50,
child: IconButton(
splashColor: Colors.transparent,
highlightColor: Colors.transparent,
hoverColor: Colors.transparent,
onPressed: () {
setState(() {
_animationIsPlayer = !_animationIsPlayer;
if (_isShowPlayer) {
_animationController.forward(from: 0);
} else {
_animationController.reverse(from: 1);
}
});
},
icon: const Icon(IconFontIcons.iconRight)),
)
]
),
}
}

感谢观看,如果对你有帮助可以关注本站,龙小亦在此谢过了