Flutter中如何使用super_context_menu插件
在Flutter项目中集成super_context_menu插件时遇到问题:按照文档添加依赖后,长按弹出的上下文菜单样式异常,无法自定义图标和文字颜色。请问如何正确配置菜单项样式?另外,如何实现在菜单项点击时获取当前Widget的上下文信息?求具体代码示例和使用注意事项。
2 回复
在Flutter中使用super_context_menu插件非常简单:
- 添加依赖:
dependencies:
super_context_menu: ^最新版本
- 基本使用:
import 'package:super_context_menu/super_context_menu.dart';
// 在Widget中包裹
SuperContextMenu(
child: YourWidget(), // 需要长按的组件
menu: ContextMenu(
children: [
MenuAction(
title: "选项1",
onSelected: () {
print("点击了选项1");
},
),
MenuAction(
title: "选项2",
onSelected: () {
print("点击了选项2");
},
),
],
),
)
- 主要特性:
- 支持长按弹出菜单
- 可自定义菜单项样式
- 支持图标、分隔线等
- 适配不同平台样式
- 注意事项:
- 确保flutter版本兼容
- 在pubspec.yaml运行flutter pub get
- 可查看官方文档获取更多配置选项
这样就完成了基础的长按菜单功能!
更多关于Flutter中如何使用super_context_menu插件的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
在Flutter中使用super_context_menu插件可以创建自定义的上下文菜单(右键菜单或长按菜单)。以下是基本使用方法:
1. 添加依赖
在pubspec.yaml文件中添加依赖:
dependencies:
super_context_menu: ^最新版本号
运行flutter pub get安装插件。
2. 基本使用
import 'package:flutter/material.dart';
import 'package:super_context_menu/super_context_menu.dart';
class MyWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return ContextMenuRegion(
contextMenu: ContextMenu(
children: [
MenuAction(
title: '复制',
onSelected: () {
// 处理复制操作
print('复制');
},
),
MenuAction(
title: '粘贴',
onSelected: () {
// 处理粘贴操作
print('粘贴');
},
),
MenuDivider(), // 分隔线
MenuAction(
title: '删除',
destructive: true, // 标记为破坏性操作(iOS上显示红色)
onSelected: () {
// 处理删除操作
print('删除');
},
),
],
),
child: Container(
width: 200,
height: 200,
color: Colors.grey[300],
alignment: Alignment.center,
child: Text('长按或右键点击我'),
),
);
}
}
3. 高级功能
- 子菜单:使用
Menu创建嵌套菜单 - 图标:通过
image属性添加图标 - 快捷键:支持设置键盘快捷键
- 平台适配:自动适配Android、iOS、Web和桌面平台
4. 完整示例
ContextMenuRegion(
contextMenu: ContextMenu(
children: [
MenuAction(
title: '新建',
image: MenuImage.icon(Icons.add),
onSelected: () => print('新建'),
),
Menu(
title: '编辑',
image: MenuImage.icon(Icons.edit),
children: [
MenuAction(
title: '剪切',
onSelected: () => print('剪切'),
),
MenuAction(
title: '复制',
onSelected: () => print('复制'),
),
],
),
],
),
child: YourWidget(),
)
注意事项
- 在Web和桌面端支持右键菜单
- 在移动端支持长按触发
- 可通过
menuStyle自定义菜单样式 - 支持菜单项启用/禁用状态控制
记得查看插件的官方文档获取最新功能和详细配置选项。

