App 流畅性的关键指标有 UI帧率,GPU帧率,我们期望它能达到 60fps,也就是16ms每帧。
以 profile / release 模式运行
为了获取最接近生产环境的数据,我们应该选择一台尽可能低端的真机,并且以 profile 模式或者 release 模式下运行app。
- 因为 debug 模式会有一些额外的检查工作,比如
assert()
等- 为了加速开发效率,debug 模式是以 JIT(Just in time)模式编译 dart 代码的,而 profile 和 release 是提前编译为机器码 AOT(Ahead Of Time),所以 debug 会慢很多
-
在 Android Studio and IntelliJ 中, 在菜单栏中点击
Run > Flutter Run main.dart in Profile Mode
-
VS Code:打开 launch.json 文件并设置flutterMode 为 profile:
“configurations”: [
{
“name”: “Flutter”,
“request”: “launch”,
“type”: “dart”,
“flutterMode”: “profile” # 测试完后记得把它改回去!
}
]
- 用命令行启动:
$ flutter run --profile
检测帧率
那么检测帧率有哪些方法呢?Flutter 给我们提供了 Performance Overlay
,如下图,绿色代表当前渲染帧。
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-N8m7mmY9-1637210371142)(https://user-gold-cdn.xitu.io/2018/12/13/167a74407691fb82?imageView2/0/w/1280/h/960/ignore-error/1)]
我们有三种开启方式
- 在Android Studio 和 IntelliJ IDEA中: 选中
View > Tool Windows > Flutter Inspector
. 点击下面这个按钮。
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-C1r8tUeQ-1637210371178)(https://user-gold-cdn.xitu.io/2018/12/13/167a744056983edb?imageView2/0/w/1280/h/960/ignore-error/1)]
-
在 VS Code中 选中
View > Command Palette…
会显示一个 command 面板. 在命令面板中输入performance
并选择Toggle Performance Overlay
如果命令显示为不可用,需要检查 app 是否正在运行. -
从命令行中运行 键盘输入
P
-
代码中打开 在
MaterialApp
或者WidgetsApp
的构造函数中设置showPerformanceOverlay
属性为true
:
class MyApp extends StatelessWidget {
@override
Wid