老孟導讀:Flutter組件有一個很大的特點,那就是不少複雜的組件都是經過一個一個小組件拼裝而成的,今天就來講說系統的ExpansionPanelList是如何實現的。git
在瞭解ExpansionPanelList實現前,先來了解下MergeableMaterial,它展現多個MergeableMaterialItem組件,當子組件發生變化時,以動畫的方式打開或者關閉子組件,MergeableMaterial的父控件須要在主軸方向是一個沒有限制的控件,好比SingleChildScrollView、Row、Column等。微信
基本用法以下:ide
SingleChildScrollView( child: MergeableMaterial( children: [ MaterialSlice( key: ValueKey(1), child: Container( height: 45, color: Colors.primaries[1 % Colors.primaries.length], )), MaterialGap(key: ValueKey(2)), MaterialSlice( key: ValueKey(3), child: Container( height: 45, color: Colors.primaries[1 % Colors.primaries.length], )), MaterialGap(key: ValueKey(4)), MaterialSlice( key: ValueKey(5), child: Container( height: 45, color: Colors.primaries[1 % Colors.primaries.length], )), ], ), )
效果以下:動畫
MergeableMaterial的子控件只能是MaterialSlice和MaterialGap,MaterialSlice是帶子控件的控件,顯示實際內容,MaterialGap用於分割,只能放在MaterialSlice中間。ui
靜態狀況下,看不出具體的效果,動態改變子組件用法以下:code
List<MergeableMaterialItem> items = []; List.generate(_count, (index) { items.add(MaterialSlice( key: ValueKey(index * 2), child: Container( height: 45, color: Colors.primaries[index % Colors.primaries.length], ))); }); return SingleChildScrollView( child: MergeableMaterial( children: items, ), )
效果以下:blog
主要看增長/刪除子組件時的動畫效果。ci
增長分割線和陰影:get
MergeableMaterial( hasDividers: true, elevation: 24, children: items, )
效果以下:博客
陰影值不能隨便設置,只能設置以下值:1, 2, 3, 4, 6, 8, 9, 12, 16, 24
此控件能夠實現什麼樣的效果呢?看下面效果:
實現代碼:
bool _expand = false; @override Widget build(BuildContext context) { return Column( children: <Widget>[ Container( height: 45, color: Colors.green.withOpacity(.3), alignment: Alignment.centerRight, child: IconButton( icon: Icon(Icons.arrow_drop_down), onPressed: () { setState(() { _expand = !_expand; }); }, ), ), _expand ? MergeableMaterial( hasDividers: true, elevation: 24, children: [ MaterialSlice( key: ValueKey(1), child: Container( height: 200, color: Colors.green.withOpacity(.3), )) ], ) : Container(), Container( height: 45, color: Colors.red.withOpacity(.3), ), ], ); }
看到這個效果是否想到了ExpansionPanelList呢?系統控件ExpansionPanelList就是使用此控件實現的。
老孟Flutter博客地址(近200個控件用法):http://laomengit.com
歡迎加入Flutter交流羣(微信:laomengit)、關注公衆號【老孟Flutter】: