flutter listview實(shí)現(xiàn)滑動(dòng)刪除——方式一

很多時(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)刪除效果

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容