code小生 一个专注大前端领域的技术平台
公众号回复Android
加入安卓技术群
观前提醒:本文假设你已经有一定的 Flutter 开发经验,对Flutter 的 Widget,RenderObject 等概念有所了解,并且知道如何开启 DevTools。
现有一个简单的汽泡动画需要实现,如下图:
一、直接通过 AnimationController 实现
当看到这个效果图的时候,很快啊,啪一下思路就来了。涉及到动画,有状态,用 StatefulWidget
,State 里创建一个 AnimationController
,用两个 Container
对应两个圈,外圈的 Container
的宽高监听动画跟着更新就行。
代码如下:
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
|
const double size = 56;class BubbleAnimationByAnimationController extends StatefulWidget {@override_BubbleAnimationByAnimationControllerState createState() => _BubbleAnimationByAnimationControllerState();
}class _BubbleAnimationByAnimationControllerState extends State<BubbleAnimationByAnimationController>with SingleTickerProviderStateMixin {AnimationController _controller;@overridevoid initState() {super.initState();_controller = AnimationController(duration: const Duration(seconds: 1),vsync: this,)..addListener(() => setState(() {}));_controller.repeat(reverse: true);}@overridevoid dispose() {_controller.dispose();super.dispose();}@overrideWidget build(BuildContext context) {// 两个 `Container` 对应两个圈return Container( alignment: Alignment.center,constraints: BoxConstraints.tight(Size.square((1 + _controller.value * 0.2) * size),),decoration: BoxDecoration(shape: BoxShape.circle,color: Colors.blue[200],),child: Container(alignment: Alignment.center,padding: const EdgeInsets.all(8.0),decoration: BoxDecoration(shape: BoxShape.circle,color: Colors.blue,),width: size,height: size,child: Text('Hello world!',style: TextStyle(color: Colors.white, fontSize: 12),),),);}
}
|
跑起来,很完美的实现了要求,如下图所示:
但且慢,仔细 review 一下代码,有没有发现,内圈的 Container
其实和动画并没有什么关系,换句话说,它并不需要跟随动画一起被 build。
用 DevTools 的 Timeline 开启Track Widgets Builds
跟踪一下,如下图所示:
可以发现,在 Build
阶段,BubbleAnimationByAnimationController 因为 setState 引发 rebuild,进而重新 build 了两个 Container
,包括内圈里的 Text
。
解决办法也很简单,把内圈的 Widget 提前构建好,外圈直接用就行了:
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
|
class BubbleAnimationByAnimationController extends StatefulWidget {final Widget child;const BubbleAnimationByAnimationController({this.child});@override_BubbleAnimationByAnimationControllerState createState() => _BubbleAnimationByAnimationControllerState();
}class _BubbleAnimationByAnimationControllerState extends State<BubbleAnimationByAnimationController>with SingleTickerProviderStateMixin {AnimationController _controller;@overridevoid initState() {super.initState();_controller = AnimationController(duration: const Duration(seconds: 1),vsync: this,)..addListener(() => setState(() {}));_controller.repeat(reverse: true);}@overridevoid dispose() {_controller.dispose();super.dispose();}@overrideWidget build(BuildContext context) {// 外圈 `Container` 包裹内圈return Container( alignment: Alignment.center,constraints: BoxConstraints.tight(Size.square((1 + _controller.value * 0.2) * size),),decoration: BoxDecoration(shape: BoxShape.circle,color: Colors.blue[200],),// 这里的 widget.child 不会 rebuildchild: widget.child,);}
}// 使用时,外部构建内圈的Widget
final Widget buble = BubbleAnimationByAnimationController(child: Container(alignment: Alignment.center,padding: const EdgeInsets.all(8.0),decoration: BoxDecoration(shape: BoxShape.circle,color: Colors.blue,),width: size,height: size,child: Text('Hello world!',style: TextStyle(color: Colors.white, fontSize: 12),),),
);
|
二、通过 AnimatedBuilder 实现
其实 Flutter 官方提供的AnimatedBuilder
就是这么做的,它将不变部分的 child 交由外部构建。
用 AnimatedBuilder 改造代码如下:
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
|
class BubbleAnimationByAnimatedBuilder extends StatefulWidget {@override_BubbleAnimationByAnimatedBuilderState createState() =>_BubbleAnimationByAnimatedBuilderState();
}class _BubbleAnimationByAnimatedBuilderStateextends State<BubbleAnimationByAnimatedBuilder>with SingleTickerProviderStateMixin {AnimationController _controller;@overridevoid initState() {super.initState();_controller = AnimationController(duration: const Duration(seconds: 1),vsync: this,);// 注意:这里不需要监听了并setState了,AnimatedBuilder 已经内部这样做了_controller.repeat(reverse: true);}@overridevoid dispose() {_controller.dispose();super.dispose();}@overrideWidget build(BuildContext context) {// 用 AnimatedBuilder 内部监听动画return AnimatedBuilder(animation: _controller,builder: (context, child) {return Container(alignment: Alignment.center,constraints: BoxConstraints.tight(Size.square((1 + _controller.value * 0.2) * size),),decoration: BoxDecoration(shape: BoxShape.circle,color: Colors.blue[200],),child: child, // 这个child 其实就是外部构建好的 内圈 `Container`);},child: Container(alignment: Alignment.center,padding: const EdgeInsets.all(8.0),decoration: BoxDecoration(shape: BoxShape.circle,color: Colors.blue,),width: size,height: size,child: Text('Hello world!',style: TextStyle(color: Colors.white, fontSize: 12),),),);}
}
|
再次跑起来,非常完美。DevTools 的 Timeline 如下图所示:
可以看到,Build 阶段完全没有 rebuild 内圈的内容,只有外圈 Container
随着 rebuild。
且慢,还没完呢,还有没有办法完全不 rebuild 呢?毕竟这个动画很简单,内圈完全不变的,只有外圈随时间累加而放大/缩小。这个外圈动画自己画行不行?
三、用 CustomPaint 实现
Flutter 提供了一个Widget 叫 CustomPaint
,它只需要我们实现一个 CustomPainter
自己往 Canvas
绘制内容。
先定义一个 CustomPainter
,根据动画的值画外圈,代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
class _BubblePainter extends CustomPainter {final Animation<double> animation;const _BubblePainter(this.animation) : super(repaint: animation);@overridevoid paint(Canvas canvas, Size size) {final center = size.center(Offset.zero);// 跟随动画放大/缩小圈的半径final radius = center.dx * (1 + animation.value * 0.2);final paint = Paint()..color = Colors.blue[200]..isAntiAlias = true;canvas.drawCircle(center, radius, paint);}@overridebool shouldRepaint(_BubblePainter oldDelegate) {return oldDelegate.animation != this.animation;}
}
|
特别注意,父类构造方法的调用不能省 super(repaint: animation)
,后面告诉你为什么。
其它代码跟之前没什么两样,如下:
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
|
class BubbleAnimationByCustomPaint extends StatefulWidget {@override_BubbleAnimationByCustomPaintState createState() =>_BubbleAnimationByCustomPaintState();
}class _BubbleAnimationByCustomPaintStateextends State<BubbleAnimationByCustomPaint>with SingleTickerProviderStateMixin {AnimationController _controller;@overridevoid initState() {super.initState();_controller = AnimationController(duration: const Duration(seconds: 1),vsync: this,);_controller.repeat(reverse: true);}@overridevoid dispose() {_controller.dispose();super.dispose();}@overrideWidget build(BuildContext context) {return CustomPaint(painter: _BubblePainter(_controller),// CustomPaint 的大小会自动使用 child 的大小child: Container(alignment: Alignment.center,padding: const EdgeInsets.all(8.0),decoration: BoxDecoration(shape: BoxShape.circle,color: Colors.blue,),width: size,height: size,child: Text('Hello world!',style: TextStyle(color: Colors.white, fontSize: 12),),),);}
}
|
跑起来,跟之前版本一样的完美。
你可能好奇了,CustomPaint
怎么会自己动起来呢?其实,秘密就在 CustomPainter
的构造方法里的 repaint
参数。
由CustomPaint
创建的 RenderObject 对象 RenderCustomPaint
会监听这个 repaint
,而该对象是外部传入的 _controller
,动画更新触发markNeedsPaint()
,进而画面动起来了。可以戳这里看一眼 RenderCustomPaint 源码。
这次 DevTools 的 Timeline 如下图所示,完全没有了 Build 的踪影:
再且慢,还没结束。到这里只是解决了 Build
阶段频繁rebuild 的问题,看上图所示,Paint
阶段似乎还能再挤几滴性能出来?
最后的最后
怎么跟踪查看 repaint 呢,总不至于打log吧?
开启 DevTools 的 Repaint RainBow
选项即可。或者在代码中设置debugRepaintRainbowEnabled = true
。
在手机画面上立马会看到色块,如果画面上有动画的话更明显,其会随着 paint 的次数增加而变化,像彩虹灯一样。如下图:
可以看到,整个 APP 界面包括头部的 AppBar
的颜色是跟着内部的汽泡一起变的,说明在随着内部动画而发生 repaint
。
Flutter 提供了一个 RepaintBoundary
用于限制重绘区域,专门用来解决此问题。
使用方式很简单,直接套在CustomPaint
外面,代码如下:
1
2
3
4
5
6
7
8
9
|
@override
Widget build(BuildContext context) {return RepaintBoundary(child: CustomPaint(painter: _BubblePainter(_controller),child: Container(...),),);
}
|
效果立杆见影,彩虹图如下图所示,只重绘了动画的区域:
相对应的,Paint 阶段耗时也很明显的降低:
结语
恭喜你,又离资深 Flutter 开发更近了一步。通过本文,你应该学会了如何让 Flutter 动画动得更有效率。关注公众号 逆锋起笔,回复 pdf,下载你需要的各种学习资料。
还在等什么呢,赶快回去按本文思路优化你项目中的动画吧。
如有更好的思路,或者其它的点,欢迎留下你的评论。
原文地址:https://yrom.net/blog/2020/11/16/optimize-animation-in-flutter/
分享 Flutter 学习总结
Flutter 是移动应用程序开发的未来?
下载!闲鱼最新升级版 Flutter 技术电子书!
点个『在看』支持下
- flutter APP中禁止软键盘弹出,监听硬键盘输入方法
flutter App中禁止软键盘弹出,监听硬键盘输入的方法 之前的工作中遇到一个需求,想点击输入框后不弹出软键盘,使用设备硬键盘输入,解决方法:设置输入框只读并且显示光标,然后配置键盘监听就可以了. ...
- 快速获取iOS APP中的所有素材
2019独角兽企业重金招聘Python工程师标准>>> 1.我们都知道最常规的获取app中的素材是通过iTunes下载应用 -> 右键show in Finder获取ipa文件 ...
- 如何快速定位Android APP中的关键函数?
需求来源 在逆向分析中,肯定是越快地定位到目标函数越好,那么有没有这样的一种工具可以快速地辅助分析人员定位到目标函数呢? 最早的一个想法是这样的: - 通过某种机制让APP输出函数调用时候的日志记录. ...
- Flutter App 软件测试指南
众所周知,应用的功能越多,手动测试的难度就越大.一套完整的自动化测试将帮助您,并确保您的应用在发布之前正确执行. 本文涵盖了 Flutter App 的所有测试方式,通过本场 Chat 的学习,您将会 ...
- 打造H5动感影集的爱恨情仇(动画性能篇)
"你听说过动感影集么?" 动感影集是QQ空间新功能,可以将静态的图片轻松转变为动态的视频集,且载体是HTML5(简称H5)页面,意味着可以随时分享到空间或朋友圈给好友欣赏! 移动端 ...
- 打造H5动感影集的爱恨情仇–动画性能篇
"你听说过动感影集么?" 动感影集是QQ空间新功能,可以将静态的图片轻松转变为动态的视频集,且载体是HTML5(简称H5)页面,意味着可以随时分享到空间或朋友圈给好友欣赏! 移动端 ...
- Flutter 动态饼状图 让你的APP中无聊的统计图动起来 挻舒适的感觉瞬间提升一个档次 -深夜创作
优美的应用体验 来自于细节的处理,更源自于码农的自我要求与努力,当然也需要码农年轻灵活的思维,不局限于思维,不局限语言限制,才是编程的最高境界. 很多人会谈论到程序员35岁的问题,在我看来,无论是程序 ...
- 京东APP中Flutter探索及优化
点击"开发者技术前线",选择"星标" 让一部分开发者先看到未来 前言 随着Flutter稳定版本逐步迭代更新,京东APP内部的Flutter业务也日益增多,Fl ...
- 如何在App中实现朋友圈功能之二快速实现用户信息的自定义——箭扣科技Arrownock...
如何在App中实现朋友圈功能 之二 快速实现用户信息的自定义 自我关联社交元素: anSocial中很多的社交元素API,如帖子(Post).相册(Album).文件(File)等,这些API的可选参 ...