import 'package:flutter/material.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: const MyHomePage(), ); } } class MyHomePage extends StatefulWidget { const MyHomePage({super.key}); @override // ignore: library_private_types_in_public_api _MyHomePageState createState() => _MyHomePageState(); } class _MyHomePageState extends State { OverlayEntry? _overlayEntry; void _showOverlay(BuildContext context, Offset position) { if (_overlayEntry != null) { _overlayEntry!.remove(); } _overlayEntry = OverlayEntry( builder: (context) => Positioned( left: position.dx, top: position.dy, child: Material( child: Container( width: 50, height: 70, color: Colors.black, child: Column( mainAxisSize: MainAxisSize.min, children: [ IconButton( icon: const Icon(Icons.delete), onPressed: () { // 在这里处理按钮点击事件 debugPrint('删除按钮点击'); _hideOverlay(); }, ), const Text( '删除', style: TextStyle(fontSize: 10, color: Colors.white), ), ], ), ), ), ), ); Overlay.of(context).insert(_overlayEntry!); } void _hideOverlay() { debugPrint("数据"); _overlayEntry?.remove(); _overlayEntry = null; } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('长按显示按钮示例'), ), body: GestureDetector( onLongPressStart: (details) { _showOverlay(context, details.globalPosition); }, onTap: _hideOverlay, child: const SizedBox( width: double.infinity, height: double.infinity, child: ListTile( title: Text('长按此项'), ), ), ), ); } }