performance - Flutter 低帧率表现
问题描述
当我启动 speed_dial 动画插件时,我看到了帧率 UI 的线性下降。当我在这里添加 sharedpref 函数时出现问题:
@override
Widget build(BuildContext context) {
sharedpref_function();
return Scaffold(
听一个保存的值,即使 sharedpref 为空,我也有这种降级。
10 分钟后没有做任何事情,当我调用 _renderSpeedDial 时测量 1120 毫秒/帧
这是完整的代码:
bool _dialVisible = true;
Color _speedDial = Colors.pink;
sharedpref_function() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
}
);
}
_renderSpeedDial() {
return SpeedDial(
animatedIcon: AnimatedIcons.add_event,
animatedIconTheme: IconThemeData(size: 22.0),
backgroundColor: _speedDial,
// child: Icon(Icons.add),
/* onOpen: () => print('OPENING DIAL'),
onClose: () => print('DIAL CLOSED'),*/
visible: _dialVisible,
curve: Curves.bounceIn,
children: [
SpeedDialChild(
child: Icon(Icons.fullscreen_exit, color: Colors.white),
backgroundColor: Color(0xffa088df),
onTap: () {
setState(() {
});
},
label: '1',
labelStyle: TextStyle(fontWeight: FontWeight.w500,color: Colors.white),
labelBackgroundColor:Color(0xffa088df),
),
],
);
}
@override
Widget build(BuildContext context) {
sharedpref_function(); // here the sharedpref I use to listen saved value
return Scaffold(
body: Stack(
children: <Widget>[
Padding
(
padding: const EdgeInsets.only(right:10.0, bottom:10.0),
child:
_renderSpeedDial(),
),
],
)
);
}
}
解决方案
您的sharedpref_function()方法正在您的构建方法中被调用。根本不建议这样做,因为它将在需要重建 UI 的每一帧上调用,并且您的代码(那里有动画)将以 60fps(每帧)调用。
将您的方法移动到initState或didChangeDependencies中(还有更多的方法会被调用一次或几次,例如didChangeDependencies)。
当您需要更新值时,您可以在onTap手势中进行操作,仅此而已。
此外,在--release
(发布模式)下测试您的应用程序以真正测试您的应用程序的速度。