ExpansionTile Widget
就是一個能夠展開閉合的組件,經常使用的屬性有以下幾個。數組
Text Widget
。代碼示例以下:app
import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title:'Flutter Demo', theme: new ThemeData.dark(), home:ExpansionTileDemo() ); } } class ExpansionTileDemo extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text('Expansion Tile Demo')), body: Center( child: ExpansionTile( title: Text('Expansion Tile'), leading: Icon(Icons.ac_unit), backgroundColor: Colors.white12, children: <Widget>[ ListTile( title: Text('list tile'), subtitle: Text('subtitle'), ), ], initiallyExpanded: true, //打開狀態 不寫默認false閉合狀態 ), ), ); } }
Flutter還很貼心的爲提供了一個ExpansionPanelList Widget,它能夠實現展開閉合的列表功能。less
注意:ExpansionPanelList要在SingleChildScrollView裏使用ide
修改上面的代碼以下:動畫
import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title:'Flutter Demo', theme: new ThemeData.dark(), //home:ExpansionTileDemo(), home: ExpansionPanelListDemo(), ); } } class ExpandStateBean{ //控制打開關閉狀態 var index,isOpen; ExpandStateBean(this.index, this.isOpen); } class ExpansionPanelListDemo extends StatefulWidget { _ExpansionPanelListDemoState createState() => _ExpansionPanelListDemoState(); } class _ExpansionPanelListDemoState extends State<ExpansionPanelListDemo> { List<int> mList; //列表數組 List<ExpandStateBean> expandStateList; //自定義ExpandStateBean的數組expandStateList _ExpansionPanelListDemoState(){ //構造方法 mList = new List(); //初始化 expandStateList = new List(); //初始化 for(int i=0; i<10; i++){ mList.add(i); expandStateList.add(ExpandStateBean(i, false)); } } _setCurrentIndex(int index, isExpand){ setState(() { expandStateList.forEach((item){ if(item.index == index){ item.isOpen = !isExpand; } }); }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text('expansion panel list'),), body: SingleChildScrollView( //可滾動的組件 child: ExpansionPanelList( expansionCallback: (index,bol){ _setCurrentIndex(index,bol); }, children: mList.map((index){ return ExpansionPanel( headerBuilder: (context,isExpanded){ return ListTile( title: Text('This is NO.$index'), ); }, body: ListTile( title: Text('expansin no.$index'), ), isExpanded: expandStateList[index].isOpen ); }).toList(), ), ), ); } }