flutter AnimationController动画
碰到的问题
最近在搞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) { _animationController.forward(from: 0); } else { _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
| 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)), ) ] ), } }
|
感谢观看,如果对你有帮助可以关注本站,龙小亦在此谢过了