首先 Flutter 是一個很是高性能的框架,所以大多時候不須要開發者作出特殊的處理,只須要避免常見的性能問題便可得到高性能的應用程序。html
在調用 setState() 方法重建組件時,必定要最小化重建組件,沒有變化的組件不要重建,看下面的Demo,這是一個設置頁面,git
import 'package:flutter/material.dart'; class SettingDemo extends StatefulWidget { @override _SettingDemoState createState() => _SettingDemoState(); } class _SettingDemoState extends State<SettingDemo> { Widget _item( {IconData iconData, Color iconColor, String title, Widget suffix}) { return Container( height: 45, child: Row( children: <Widget>[ SizedBox( width: 30, ), Icon( iconData, color: iconColor, ), SizedBox( width: 30, ), Expanded( child: Text('$title'), ), suffix, SizedBox( width: 15, ), ], ), ); } bool _switchValue = false; @override Widget build(BuildContext context) { return Column( children: <Widget>[ _item( iconData: Icons.notifications, iconColor: Colors.blue, title: '是否容許4G網絡下載', suffix: Switch( value: _switchValue, onChanged: (value) { setState(() { _switchValue = value; }); }), ), Divider(), _item( iconData: Icons.notifications, iconColor: Colors.blue, title: '消息中心', suffix: Text( '12條', style: TextStyle(color: Colors.grey.withOpacity(.5)), ), ), Divider(), _item( iconData: Icons.thumb_up, iconColor: Colors.green, title: '我贊過的', suffix: Text( '121篇', style: TextStyle(color: Colors.grey.withOpacity(.5)), ), ), Divider(), _item( iconData: Icons.grade, iconColor: Colors.yellow, title: '收藏集', suffix: Text( '2個', style: TextStyle(color: Colors.grey.withOpacity(.5)), ), ), Divider(), _item( iconData: Icons.account_balance_wallet, iconColor: Colors.blue, title: '個人錢包', suffix: Text( '10萬', style: TextStyle(color: Colors.grey.withOpacity(.5)), ), ), ], ); } }
注意看上圖右邊下半部分,點擊切換開關的時候,全部的組件所有重建了,理想狀況下,應該只是 Switch 組件進行切換,所以將 Switch 組件進行封裝:github
class _SwitchWidget extends StatefulWidget { final bool value; const _SwitchWidget({Key key, this.value}) : super(key: key); @override __SwitchWidgetState createState() => __SwitchWidgetState(); } class __SwitchWidgetState extends State<_SwitchWidget> { bool _value; @override void initState() { _value = widget.value; super.initState(); } @override Widget build(BuildContext context) { return Switch( value: _value, onChanged: (value) { setState(() { _value = value; }); }, ); } }
使用:api
_item( iconData: Icons.notifications, iconColor: Colors.blue, title: '是否容許4G網絡下載', suffix: _SwitchWidget( value: false, ), )
此時看到重建的組件只有 _SwitchWidget 和 Switch 組件,提升了性能。緩存
若是 Switch 組件的狀態改變也會改變其它組件的狀態,這是典型的組件間通訊,這種狀況下可使用 InheritedWidget,但更建議使用狀態管理框架(好比 Provider 等),而不是將其父組件改變爲StatefulWidget。微信
儘可能不要將整個頁面定義爲 StatefulWidget 組件,由於一旦重建將重建此頁面下全部的組件,尤爲是 Switch 、Radio等組件狀態的改變致使的重建,強烈建議對其進行封裝。網絡
這裏有一個誤區,有些人認爲,將組件拆分爲方法能夠減小重建,就好比上面的例子,將 _SwitchWidget 組件改變爲方法,該方法返回 Switch 組件,這是錯誤的,此種方式並不能減小重建, 可是將一個組件拆分爲多個小組件是能夠減小重建的,就像上面的例子,將須要重建的 Switch 封裝爲一個單獨的 StatefulWidget 組件,避免了其餘沒必要要的重建。框架
在組件前加上 const ,至關於對此組件進行了緩存,下面是未加 const 的代碼:ide
class ConstDemo extends StatefulWidget { @override _ConstDemoState createState() => _ConstDemoState(); } class _ConstDemoState extends State<ConstDemo> { @override Widget build(BuildContext context) { return Center( child: Column( children: [ Text('老孟'), RaisedButton(onPressed: (){ setState(() { }); }) ], ), ); } }
給 Text('老孟') 組件加上 const:性能
const Text('老孟'),
對比兩次 Text 組件的重建狀況,加上 const 後,未重建。
有以下場景,有一個 Text 組件有可見和不可見兩種狀態,代碼以下:
bool _visible = true; @override Widget build(BuildContext context) { return Center( child: Column( children: [ if(_visible) Text('可見'), Container(), ], ), ); }
可見時的組件樹:
不可見時的組件樹:
兩種狀態組件樹結構發生變化,應該避免發生此種狀況,優化以下:
Center( child: Column( children: [ Visibility( visible: _visible, child: Text('可見'), ), Container(), ], ), )
此時不論是可見仍是不可見狀態,組件樹都不會發生變化,以下:
還有一種狀況是根據不一樣的條件構建不一樣的組件,以下:
bool _showButton = true; @override Widget build(BuildContext context) { return Center( child: Column( children: [ _showButton ? RaisedButton(onPressed: null) : Text('不顯示'), Container(), ], ), ); }
設置爲 true 時的組件樹結構:
設置爲 false 時的組件樹結構:
看到左側子節點由 RaisedButton 變爲了 Text。
上面的狀況組件樹發生了更改,不論是類型發生更改,仍是深度發生更改,若是沒法避免,那麼就將變化的組件樹封裝爲一個 StatefulWidget 組件,且設置 GlobalKey,以下:
封裝變化的部分:
class ChildWidget extends StatefulWidget { const ChildWidget({Key key}) : super(key: key); @override _ChildWidgetState createState() => _ChildWidgetState(); } class _ChildWidgetState extends State<ChildWidget> { bool _showButton = true; @override Widget build(BuildContext context) { return _showButton ? RaisedButton(onPressed: null) : Text('不顯示'); } }
構建:
class ConstDemo extends StatefulWidget { @override _ConstDemoState createState() => _ConstDemoState(); } class _ConstDemoState extends State<ConstDemo> { @override Widget build(BuildContext context) { return Center( child: Column( children: [ ChildWidget(key: GlobalKey(),), Container(), ], ), ); } }
雖然經過 GlobalKey 提升了上面案例的性能,但咱們千萬不要亂用 GlobalKey,由於管理 GlobalKey 的成本很高,因此其餘須要使用 Key 的地方建議考慮使用 Key, ValueKey, ObjectKey, 和 UniqueKey。
關於 GlobalKey 的相關說明參考:https://api.flutter.dev/flutter/widgets/GlobalKey-class.html
ListView是咱們最經常使用的組件之一,用於展現大量數據的列表。若是展現大量數據請使用 ListView.builder 或者 ListView.separated,千萬不要直接使用以下方式:
ListView( children: <Widget>[ item,item1,item2,... ], )
這種方式一次加載全部的組件,沒有「懶加載」,消耗極大的性能。
ListView 中 itemExtent 屬性對動態滾動到性能提高很是大,好比,有2000條數據展現,點擊按鈕滾動到最後,代碼以下:
class ListViewDemo extends StatefulWidget { @override _ListViewDemoState createState() => _ListViewDemoState(); } class _ListViewDemoState extends State<ListViewDemo> { ScrollController _controller; @override void initState() { super.initState(); _controller = ScrollController(); } @override Widget build(BuildContext context) { return Stack( children: [ ListView.builder( controller: _controller, itemBuilder: (context, index) { return Container( height: 80, alignment: Alignment.center, color: Colors.primaries[index % Colors.primaries.length], child: Text('$index',style: TextStyle(color: Colors.white,fontSize: 20),), ); }, itemCount: 2000, ), Positioned( child: RaisedButton( child: Text('滾動到最後'), onPressed: () { _controller.jumpTo(_controller.position.maxScrollExtent); }, )) ], ); } }
耗時在2秒左右,加上 itemExtent 屬性,修改以下:
ListView.builder( controller: _controller, itemBuilder: (context, index) { return Container( height: 80, alignment: Alignment.center, color: Colors.primaries[index % Colors.primaries.length], child: Text('$index',style: TextStyle(color: Colors.white,fontSize: 20),), ); }, itemExtent: 80, itemCount: 2000, )
優化後瞬間跳轉到底部。
這是由於不設置 itemExtent 屬性,將會由子組件本身決定大小,大量的計算致使UI堵塞。
這裏說的是向AnimatedBuilder 、TweenAnimationBuilder 等一類的組件的問題,這些組件都有一個共同點,帶有 builder 且其參數重有 child。
以 AnimatedBuilder 爲例,若是 builder 中構建的樹中包含與動畫無關的組件,將這些無關的組件看成 child 傳遞到 builder 中比直接在 builder 中構建更加有效。
好比下面的代碼,直接在 builder 中構建子組件:
AnimatedBuilder( animation: animation, builder: (BuildContext context, Widget child) { return Transform.rotate( angle: animation.value, child: FlutterLogo(size: 60,), ); }, )
優化後的代碼:
AnimatedBuilder( animation: animation, builder: (BuildContext context, Widget child) { return Transform.rotate( angle: animation.value, child: child, ); }, child: FlutterLogo(size: 60,), )
部分組件必定要謹慎使用,由於這些組件包含一些昂貴的操做,好比 saveLayer() 方法。
調用saveLayer()會分配一個屏幕外緩衝區。 將內容繪製到屏幕外緩衝區中可能會觸發渲染目標切換,這在較早的GPU中特別慢。
另外雖然下面這些組件比較消耗性能,但並非禁止你們使用,而是謹慎使用,若是有替代方案,考慮使用替代方法。
尤爲注意,若是這些組件頻繁重建(好比動畫的過程),要重點優化。
Clip 類組件是經常使用的裁剪類組件,好比:ClipOval、ClipPath、ClipRRect、ClipRect、CustomClipper。這些組件中都有 clipBehavior 屬性,不一樣的值性能是不一樣的,
/// * [hardEdge], which is the fastest clipping, but with lower fidelity. /// * [antiAlias], which is a little slower than [hardEdge], but with smoothed edges. /// * [antiAliasWithSaveLayer], which is much slower than [antiAlias], and should /// rarely be used.
越往下,速度越慢。
一些簡單的圓角組件的設置可使用 Container 實現:
Container( height: 200, width: 200, decoration: BoxDecoration( image: DecorationImage( image: NetworkImage( 'https://flutter.github.io/assets-for-api-docs/assets/widgets/owl-2.jpg'), fit: BoxFit.cover, ), border: Border.all( color: Colors.blue, width: 2, ), borderRadius: BorderRadius.circular(12), ), )
Opacity 組件的功能是使子組件透明。此類將其子級繪製到中間緩衝區中,而後將子級混合回到部分透明的場景中。
對於除0.0和1.0以外的不透明度值,此類相對昂貴,由於它須要將子級繪製到中間緩衝區中。 對於值0.0,根本不繪製子級。 對於值1.0,將當即繪製沒有中間緩衝區的子對象。
若是僅僅是對單個 Image 或者 Color 增長透明度,直接使用比 Opacity 組件更快:
Container(color: Color.fromRGBO(255, 0, 0, 0.5))
比使用 Opacity 組件更快:
Opacity(opacity: 0.5, child: Container(color: Colors.red))
若是對組件的透明度進行動畫操做,建議使用 AnimatedOpacity。
還有一些組件也要慎重使用,好比:
文中若是有不完善或者不正確的地方歡迎提出意見,後面若是優化的補充將會在個人博客中進行補充,地址:
http://laomengit.com/blog/20201227/improve_performance.html
參考連接:
https://flutter.dev/docs/perf/rendering/best-practices
https://api.flutter.dev/flutter/widgets/Opacity-class.html#transparent-image
https://api.flutter.dev/flutter/widgets/StatefulWidget-class.html#performance-considerations
老孟Flutter博客(330個控件用法+實戰入門系列文章):http://laomengit.com
添加微信或者公衆號領取 《330個控件大全》和 《Flutter 實戰》PDF。
歡迎加入Flutter交流羣(微信:laomengit)、關注公衆號【老孟Flutter】:
![]() |
![]() |