在寫業務的時候,不免有***搜索***功能,通常搜索功能的頁面以下:git
那若是在Android上面寫的話,github
通常來說是一個 RecyclerView + 自動換行的 layoutManager + 自定義的background。app
固然這個自動換行的LayoutManager 還得本身定義,去算座標。ide
那 Flutter 提供給咱們很方便的控件 Wrap + Chip,用這兩個就能輕鬆實現上訴效果。函數
先來講一下Wrap。佈局
看名字咱們也能看出來,它就是一個包裹住子佈局的 Widget,而且能夠自動換行。ui
先看一下構造函數,來肯定一下須要傳入什麼參數:this
Wrap({
Key key,
this.direction = Axis.horizontal, // 子佈局排列方向
this.alignment = WrapAlignment.start, // 子佈局對齊方向
this.spacing = 0.0, // 間隔
this.runAlignment = WrapAlignment.start, // run 能夠理解爲新的一行,新的一行的對齊方向
this.runSpacing = 0.0, // 兩行的間距
this.crossAxisAlignment = WrapCrossAlignment.start,
this.textDirection,
this.verticalDirection = VerticalDirection.down,
List<Widget> children = const <Widget>[],
}) : super(key: key, children: children);
複製代碼
最基本的咱們只須要傳入一個children便可,可是咱們想要好的效果,通常都會傳入 spacing 和 runSpacing。spa
下面看一下 Chip,Chip能夠理解爲碎片的意思,仍是先來看一下構造函數:3d
Chip({
Key key,
this.avatar,//左側Widget,通常爲小圖標
@required this.label,//標籤
this.labelStyle,
this.labelPadding,
this.deleteIcon//刪除圖標
this.onDeleted//刪除回調,爲空時不顯示刪除圖標
this.deleteIconColor//刪除圖標的顏色
this.deleteButtonTooltipMessage//刪除按鈕的tip文字
this.shape//形狀
this.clipBehavior = Clip.none,
this.backgroundColor//背景顏色
this.padding, // padding
this.materialTapTargetSize//刪除圖標material點擊區域大小
})
複製代碼
能夠看到這裏東西仍是很多的,最基本的要傳入一個label。
label 通常就爲咱們的 text,先來看一下只定義一個 label 的效果:
下面再加入 avatar:
再來加入 delete:
這裏注意,必定要設置上 onDeleted 參數,不然不顯示delete控件。
前面都是在 children 裏添加widget 來達到目的,很差作刪除工做。
如今咱們來使用 ListView,並添加刪除事件。
代碼以下:
import 'package:flutter/material.dart';
class WrapPage extends StatefulWidget {
@override
_WrapPageState createState() => _WrapPageState();
}
class _WrapPageState extends State<WrapPage> {
// 生成歷史數據
final List<String> _list = List<String>.generate(10, (i) => 'chip$i');
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('WrapPage'),
),
body: Wrap(
spacing: 10,
runSpacing: 5,
children: _list.map<Widget>((s) {
return Chip(
label: Text('$s'),
avatar: Icon(Icons.person),
deleteIcon: Icon(
Icons.close,
color: Colors.red,
),
onDeleted: () {
setState(() {
_list.remove(s); // 刪除事件
});
},
);
}).toList()
));
}
}
複製代碼
效果以下:
Flutter 提供給咱們不少好用的 widget, 咱們只須要組合起來就能夠達到咱們的目的。
完整代碼已經傳至GitHub:github.com/wanglu1209/…