import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: MenuAnchor(
child: Text('点击我显示菜单'),
itemBuilder: (BuildContext context) {
return <PopupMenuEntry<String>>[
PopupMenuItem<String>(
value: '选项1',
child: Text('选项1')
),
PopupMenuItem<String>(
value: '选项2',
child: Text('选项2')
),
// 多级菜单项
PopupSubMenuItem<String>(
initialValue: '子选项1',
itemBuilder: (BuildContext context) {
return <PopupMenuEntry<String>>[
PopupMenuItem<String>(
value: '子选项1',
child: Text('子选项1')
),
PopupMenuItem<String>(
value: '子选项2',
child: Text('子选项2')
),
];
},
child: Text('子菜单')
),
];
},
),
);
}
}
// 扩展的MenuAnchor组件,用于处理多级菜单的逻辑
class MenuAnchor extends StatefulWidget {
final Widget child;
final ValueChanged<String> onSelected;
final ItemBuilder<String> itemBuilder;
MenuAnchor({
Key key,
@required this.child,
@required this.onSelected,
@required this.itemBuilder,
}) : super(key: key);
@override
_MenuAnchorState createState() => _MenuAnchorState();
}
class _MenuAnchorState extends State<MenuAnchor> {
String _selectedValue;
void _showMenu() {
final PopupMenuThemeData popupMenuTheme = PopupMenuTheme.of(context).popupMenuTheme;
final RenderBox button = context.findRenderObject();
final Offset position = button.localToGlobal(
button.size.center(Offset.zero),
ancestor: button.owner.context.findRenderObject(),
);
showMenu<String>(
context: context,
elevation: 8.0,
items: widget.itemBuilder(context),
position: position,
theme: popupMenuTheme,
).then<void>((String newValue) {
if (newValue == null) {
// 用户取消选择
widget.onSelected('');
} else {
widget.onSelected(newValue);
setState(() {
_selectedValue = newValue;
});
}
});
}
@override
Widget build(Buil
评论已关闭