Flutter 中的 FilterChip 小部件:全面指南
在 Flutter 中,FilterChip
是一種特殊類型的 Chip
,用于呈現過濾選項。用戶可以通過點擊 FilterChip
來應用相應的過濾條件,這在需要對列表或集合進行篩選的場景中非常有用,如在電商應用中篩選商品,或在新聞應用中根據類別篩選文章。
基礎用法
FilterChip
最基本的用法是顯示一段文本,并且允許用戶點擊以應用過濾:
FilterChip(label: Text('Basic FilterChip'),onSelected: (bool selected) {// 當 FilterChip 被點擊時執行的操作},
)
自定義樣式
FilterChip
提供了多種屬性來定制其外觀:
背景顏色
backgroundColor
: 設置FilterChip
的背景顏色。
FilterChip(label: Text('Colored FilterChip'),backgroundColor: Colors.blue,onSelected: (bool selected) {/* ... */},
)
前景色
foregroundColor
: 設置FilterChip
的前景色,如文本顏色。
FilterChip(label: Text('White Text FilterChip'),foregroundColor: Colors.white,backgroundColor: Colors.blue,onSelected: (bool selected) {/* ... */},
)
標簽
label
: 設置FilterChip
的標簽,可以是任意的 Widget。
FilterChip(label: Text('Custom Label FilterChip'),onSelected: (bool selected) {/* ... */},
)
選中狀態
selected
: 定義FilterChip
是否被選中。onSelected
: 設置當FilterChip
被點擊時的回調。
FilterChip(label: Text('Selectable FilterChip'),selected: true,onSelected: (bool selected) {// 處理選中狀態改變},
)
實例:帶有圖標的 FilterChip
FilterChip
可以包含圖標,例如在標簽的前面或后面:
FilterChip(prefix: Icon(Icons.local_offer), // 前綴圖標label: Text('FilterChip with Icon'),onSelected: (bool selected) {/* ... */},
)
實例:篩選條件
FilterChip
可以用來展示篩選條件,允許用戶通過點擊來選擇或取消選擇:
FilterChip(label: Text('Discounts'),selected: discountsFilterActive, // 假設這是一個布爾值onSelected: (bool value) {// 更新篩選條件的狀態setState(() {discountsFilterActive = value;});},
)
實例:動態 FilterChip
可以動態創建 FilterChip
列表,根據篩選項的數量或用戶的選擇動態添加或移除 FilterChip
:
List<String> _selectedFilters = [];
Widget build(BuildContext context) {return Wrap(children: filters.map((filter) {return FilterChip(label: Text(filter),selected: _selectedFilters.contains(filter),onSelected: (bool selected) {setState(() {if (selected) {_selectedFilters.add(filter);} else {_selectedFilters.remove(filter);}});},);}).toList(),);
}
結語
FilterChip
是 Flutter 中一個實用的小部件,它提供了一種直觀的方式來展示和操作篩選條件,特別適合用于需要篩選功能的界面。掌握 FilterChip
的使用,可以幫助你創建出既美觀又交互性強的用戶界面,提升應用的用戶體驗。