Flutter Listview点击事件和长按事件实现

    技术2022-07-10  117

    前言:

    在Android 和iOS 常用APP经常有listview列表组件 展示数据 以及点击事件和长按事件的处理 今天我们来讲下flutter里面的子元素item的点击事件和长按事件

    效果图:

    1准备工作 需要用到的三方库

    toast: ^0.1.5 在pubspec.yaml文件中添加依赖 然后在控制台敲 flutter pub get 来下载依赖

    2 具体实现 :

    具体代码 :

    import 'package:flutter/material.dart'; import 'ToastUtil.dart'; class Listviewextends StatefulWidget { Listview({Key key}) :super(key: key); @override _ListviewStatecreateState() { return _ListviewState(); } } class _ListviewStateextends State { @override void initState() { super.initState(); } @override void dispose() { super.dispose(); } @override Widgetbuild(BuildContext context) { // TODO: implement build return Scaffold( appBar:AppBar( title:Text("listview"), ), body:LayOut(), ); } } class LayOutextends StatefulWidget { LayOut({Key key}) :super(key: key); @override _LayOutStatecreateState() { return _LayOutState(); } } class _LayOutStateextends State { @override void initState() { super.initState(); } @override void dispose() { super.dispose(); } @override Widgetbuild(BuildContext context) { // TODO: implement build return ListView.builder( itemCount:20, itemBuilder: (BuildContext context, int position){ return getItem(position); }); } WidgetgetItem(int index){ return GestureDetector( child:Container( height:40, child:Text("掏粪男孩"), ), //item 点击事件 onTap: (){ print("点击到第"+index.toString()); setState(() { onItemClick(index); }); }, //item 长按事件 onLongPress: (){ setState(() { _onItemLongPressed(index); }); print("长按"+index.toString()); } ); } void onItemClick(int index){ ToastUtil.showinfo(context, "你点击到第"+index.toString()+"条数据"); } ///* item长按 void _onItemLongPressed(int index) { setState(() { showCustomDialog(context,index); }); } void showCustomDialog(BuildContext context,int position ){ print("position ---- > "+position.toString()); showDialog( context: context, builder: (BuildContext context) { return new AlertDialog( title:new Text("点击提示"), content:new SingleChildScrollView( child:new ListBody(children: [new Text("${"点击到第"+position.toString()+"条数据"}")])), actions: [ new FlatButton( child:new Text("取消"), onPressed: () { Navigator.of(context).pop(); }, ), new FlatButton( child:new Text("确认"), onPressed: (){ Navigator.of(context).pop(); }, ), ], ); }) } }

    这里我们通过 ListView.builder 添加20条数据 显示20条text 然后在GestureDetector 组件里面 分别item 点击事件方法 onTap (点击事件方法) onLongPress(长按事件) 进行处理 点击item 我们toast 弹出当前点击到那一条数据

    void onItemClick(int index){ ToastUtil.showinfo(context, "你点击到第"+index.toString()+"条数据"); }

    长按我们对 onLongPress()进行处理

    void _onItemLongPressed(int index) { setState(() { showCustomDialog(context,index); }); }

    长按我们弹出dialog做提示处理 到此我们对listview item的点击事件和长按事件 就讲完了 主要是对GestureDetector 类里面的onTap 点击事件方法 以及·onLongPress 长按事件 的实现 进行我们具体的业务处理

    最后总结:

    listview item点击事件和 长按事件实现相对简单 对比原生写法也更简洁 ,希望我的代码能帮助到大家,我也是一个flutter学习的新手 有兴趣的同学可以私聊多多交流 交流QQ群 :515980159 个人 QQ/微信:1693891473

    QQ 交流群:

    Processed: 0.014, SQL: 9