很多時(shí)候列表需要做滑動(dòng)刪除功能,在flutter中官方也有相應(yīng)的控件Dismissible可以方便做到這一功能,但有些時(shí)候這個(gè)控件和我們需要做的功能不太符合,所有我們就需要自己動(dòng)手去實(shí)現(xiàn)了
方式:
1.使用Dismissible。
2.自己動(dòng)手實(shí)現(xiàn)。
下面先介紹第一種方式Dismissible,首先看一下效果

image
那接下來(lái)看一下代碼是怎么實(shí)現(xiàn)的:
''' 很多時(shí)候列表需要做滑動(dòng)刪除功能,在flutter中官方也有相應(yīng)的控件Dismissible可以方便做到這一功能,但有些時(shí)候這個(gè)控件和我們需要做的功能不太符合,所有我們就需要自己動(dòng)手去實(shí)現(xiàn)了
方式:
1.使用Dismissible。
2.自己動(dòng)手實(shí)現(xiàn)。
下面先介紹第一種方式Dismissible,首先看一下效果
[圖片上傳中...(image-b31479-1578306703446-0)]
那接下來(lái)看一下代碼是怎么實(shí)現(xiàn)的:
class ListRemoveFirstPage extends StatefulWidget {
@override
_ListRemoveFirstPageState createState() => _ListRemoveFirstPageState();
}
class _ListRemoveFirstPageState extends State<ListRemoveFirstPage> {
List<Result> listBank=new List();
int positionNow=0;
List<GlobalKey<RemoveItemState>> listKey=[];//通過(guò)給各個(gè)item設(shè)置key,點(diǎn)擊其它item的時(shí)候,打開的item關(guān)閉
@override
void initState(){
super.initState();
initList();
}
void initList(){
listBank=List.generate(10, (index){
Result result=new Result("title $index","detail $index");
return result;
});
updateView(listBank);
}
void updateView(List<Result> list){
listKey.clear();
listKey.addAll(setKey(list.length));
setState(() {});
}
List<GlobalKey<RemoveItemState>> setKey(int length){
var list=<GlobalKey<RemoveItemState>>[];
for (int i = 0; i < length; i++) {
var key=GlobalKey<RemoveItemState>();
list.add(key);
}
return list;
}
@override
Widget build(BuildContext context) {
return Scaffold(appBar: AppBar(title: Text("List滑動(dòng)刪除"),centerTitle: true,elevation:0),
body:ListView.builder(itemCount:listBank.length,itemBuilder: (BuildContext context, int index){
return Dismissible(key: listKey[index],//如果Dismissible是一個(gè)列表項(xiàng) 它必須有一個(gè)key 用來(lái)區(qū)別其他項(xiàng)
background: new Container(color: Colors.red,margin: EdgeInsets.only(top: 15),),
// 滑動(dòng)回調(diào)
onDismissed: (direction) {
// 根據(jù)位置移除
positionNow=index;
_deleteBank();
// 提示
Scaffold.of(context).showSnackBar(SnackBar(content: Text("已移除 $positionNow")));
},
child:Container(height:100,padding: EdgeInsets.only(top: 15),width:MediaQuery.of(context).size.width,child: RemoveWidget(listBank[index]),) );
}),
);
}
代碼很簡(jiǎn)單,需要注意的是Dismissible要設(shè)置key 否則會(huì)報(bào)錯(cuò)。
下一篇介紹如何手動(dòng)實(shí)現(xiàn)有刪除按鈕的滑動(dòng)刪除效果