下面是一个使用Flutter CupertinoContextMenu的示例代码:
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
class CupertinoContextMenuDemo extends StatefulWidget {
const CupertinoContextMenuDemo({Key? key}) : super(key: key);
@override
_CupertinoContextMenuDemoState createState() =>
_CupertinoContextMenuDemoState();
}
class _CupertinoContextMenuDemoState extends State<CupertinoContextMenuDemo> {
final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
String _selectedAction = "None";
@override
Widget build(BuildContext context) {
return Scaffold(
key: _scaffoldKey,
appBar: CupertinoNavigationBar(
middle: Text("CupertinoContextMenu"),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text("Selected Action: $_selectedAction"),
SizedBox(height: 20),
CupertinoContextMenu(
child: Container(
height: 200,
width: 200,
color: Colors.blue,
child: Center(
child: Text(
"Long press to show context menu",
style: TextStyle(color: Colors.white),
),
),
),
actions: <Widget>[
CupertinoContextMenuAction(
child: const Text('Copy'),
onPressed: () {
setState(() {
_selectedAction = "Copy";
});
},
),
CupertinoContextMenuAction(
child: const Text('Cut'),
onPressed: () {
setState(() {
_selectedAction = "Cut";
});
},
),
CupertinoContextMenuAction(
child: const Text('Paste'),
onPressed: () {
setState(() {
_selectedAction = "Paste";
});
},
),
],
),
],
),
),
);
}
}
在这个示例中,我们将CupertinoContextMenu嵌套在一个Container中,然后绑定了一些操作(复制、剪切、粘贴)来展示上下文菜单。当用户长按Container时,上下文菜单将出现并显示可能的操作,用户可以选择一个他们想执行的操作。如果操作被选中,则我们将 setState() 用于更新选择操作的状态。