Flutter 中listview 点击事件和长按事件实现
2020-01-10 本文已影响0人
xq9527
前言:
在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做提示处理
