Android-自定义PopupWindow,flutter开发实战详解pdf
在Flutter中,自定义PopupWindow
可以通过OverlayEntry
来实现。以下是一个简单的自定义PopupWindow
的示例代码:
import 'package:flutter/material.dart';
class CustomPopupWindow extends StatefulWidget {
@override
_CustomPopupWindowState createState() => _CustomPopupWindowState();
}
class _CustomPopupWindowState extends State<CustomPopupWindow> {
OverlayEntry? _overlayEntry;
bool _isPopupShowing = false;
void _showPopup(BuildContext context) {
if (_overlayEntry != null) return;
RenderBox renderBox = context.findRenderObject() as RenderBox;
var size = renderBox.size;
var offset = renderBox.localToGlobal(Offset.zero);
_overlayEntry = OverlayEntry(builder: (context) {
return Positioned(
left: offset.dx,
top: offset.dy + size.height,
width: size.width,
child: Material(
color: Colors.white,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
ListTile(
title: Text('选项一'),
onTap: () {
// 处理选项点击事件
_removePopup();
},
),
ListTile(
title: Text('选项二'),
onTap: () {
// 处理选项点击事件
_removePopup();
},
),
// 其他选项...
],
),
),
);
});
Overlay.of(context).insert(_overlayEntry!);
setState(() {
_isPopupShowing = true;
});
}
void _removePopup() {
_overlayEntry?.remove();
_overlayEntry = null;
setState(() {
_isPopupShowing = false;
});
}
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
if (_isPopupShowing) {
_removePopup();
} else {
_showPopup(context);
}
},
child: Container(
alignment: Alignment.center,
color: Colors.blue,
child: Text(
'点击显示Popup',
style: TextStyle(color: Colors.white),
),
),
);
}
}
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('自定义PopupWindow示例'),
),
body: Center(
child: CustomPopupWindow(),
评论已关闭