flutter 点击位置弹出菜单栏(仿微信文本长按位置下方弹出菜单)

效果图:
https://s33.aconvert.com/convert/p3r68-cdx67/lmhbo-7mv6u.gif
在这里插入图片描述

在这里插入图片描述
代码:
import ‘package:flutter/material.dart’;

class PopupMenu extends StatefulWidget {
@override
State createState() => _PopupMenuState();
}

class _PopupMenuState extends State {
Color bgColor = Colors.white;
GlobalKey anchorKey = GlobalKey();
@override
Widget build(BuildContext context) {
return GestureDetector(
child: Text(
‘张明月最近一直在加班,苦逼苦逼苦逼~~~’,
style: TextStyle(backgroundColor: bgColor,height: 1.5,fontSize: 15),
key:anchorKey ,
),
onLongPressStart: (detail) {
bgColor = Colors.grey;
setState(() {});
_showMenu(context, detail);
},
);
}

PopupMenuButton _popMenu() {
return PopupMenuButton(
itemBuilder: (context) => _getPopupMenu(context),
onSelected: (String value) {
print(‘onSelected’);
_selectValueChange(value);
},
onCanceled: () {
print(‘onCanceled’);
bgColor = Colors.white;
setState(() {});
},
);
}

_selectValueChange(String value) {
setState(() {});
}

_showMenu(BuildContext context, LongPressStartDetails detail) {
RenderBox renderBox = anchorKey.currentContext.findRenderObject();
var offset = renderBox.localToGlobal(Offset(0.0, renderBox.size.height));
final RelativeRect position = RelativeRect.fromLTRB(
detail.globalPosition.dx,//取点击位置坐弹出x坐标
offset.dy,//取text高度做弹出y坐标(这样弹出就不会遮挡文本)
detail.globalPosition.dx,
offset.dy);
var pop = _popMenu();
showMenu(
context: context,
items: pop.itemBuilder(context),
position: position,//弹出框位置
).then((String newValue) {
if (!mounted) return null;
if (newValue == null) {
if (pop.onCanceled != null) pop.onCanceled();
return null;
}
if (pop.onSelected != null) pop.onSelected(newValue);
});
}

_getPopupMenu(BuildContext context) {
return <PopupMenuEntry>[
PopupMenuItem(
value: ‘复制’,
child: Text(‘复制’),
),
PopupMenuItem(
value: ‘收藏’,
child: Text(‘收藏’),
),
];
}
}

好了 去玩吧

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值