Flutter中的key和GlobalKey


我們都知道flutter都是通過setState重新渲染build,實現數據和UI的更新;然而一個界面有時候需要更新的內容較少,而重新build,會大大的影響性能問題。因此,flutter有一個增量渲染的機制,去對數據發生變的進行增量更新。
接下來我們就來講述一下flutter增量更新常用到的key和GlobalKey的使用。

之前我們講述過flutter的渲染流程,他有三顆重要的樹,widget樹,element樹,Render樹。
而flutter更新數據時,會拿widget現有數據與element之前保存的數據進行比較,通過發現數據是否發生變化,來更新數據。
下面我們通過案例來實現一下這個過程。

我們先用StateleffWidget來做一個實驗。

下面的代碼是創建一個隨機顏色的正方形塊。

class Itemless extends StatelessWidget{
final title;
Itemless({this.title});
final _color = Color.fromRGBO(
Random().nextInt(256), Random().nextInt(256), Random().nextInt(256), 1.0);

@override
Widget build(BuildContext context) {
// TODO: implement build
return Container(
width: 100,
height: 100,
color: _color,
child: Center(
child: Text(title),
),
);
}
}
我們通過在界面上點擊按鈕,來減少正方形塊,看看顏色的變化。

class keyDemo extends StatefulWidget{

@override
_keyDemoState createState() => _keyDemoState();
}
class _keyDemoState extends State {

List items = [
Itemless(title:'aaaaa'),
Itemless(title:'bbbbb'),
Itemless(title:'ccccc'),

//StateItem('aaaaa',key: ValueKey(1111),),
//StateItem('bbbbb',key:ValueKey(2222),),
//StateItem('ccccc',key:ValueKey(3333),),

];
@override
Widget build(BuildContext context) {
// TODO: implement build
return Scaffold(
appBar: AppBar(
title: Text('keyDemo'),
),
body: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: items,
),
floatingActionButton: FloatingActionButton(
onPressed: (){
setState(() {
items.removeAt(0);
});
},
child: Icon(Icons.add),
),
);
}
}

上面的代碼主要是通過點擊floatbtn來減少數組中第0個數據,通過運行程序,一切正常,每次遞減都是從第0個開始,每個方塊的顏色和內容不會發生改變。

下面我們用StatefulWidget來實現一下上面的功能。

關鍵代碼

class StateItem extends StatefulWidget{
final title;
StateItem(this.title);
//StateItem(this.title,{Key key}):super(key: key);

_StateItemState createState() => _StateItemState();

}
class _StateItemState extends State {
final _color = Color.fromRGBO(Random().nextInt(256), Random().nextInt(256), Random().nextInt(256), 1.0);
@override
Widget build(BuildContext context) {
// TODO: implement build
return Container(
width: 100,
height: 100,
color: _color,
child: Center(
child: Text(widget.title),
),
);

}
}

作者:大橘豬豬俠
鏈接:https://www.jianshu.com/p/8b7b14f69636
來源:簡書
著作權歸作者所有。商業轉載請聯系作者獲得授權,非商業轉載請注明出處。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM