Flutter 系列文章 总体目录
属性 | 说明 |
---|---|
itemBuilder | item子项 |
initialValue | 初始值 |
onSelected | 选择其中一项时回调 |
onCanceled | 点击空白处,不选择时回调 |
tooltip | 提示 |
elevation | Z轴阴影 |
child | 子控件,不能和icon都设置 |
icon | IconButton子控件, 不能和child都设置 |
除了和AppBar同时使用外,还可以点击Button显示。
import 'package:flutter/material.dart';
class PopupMenuButtonDemo extends StatefulWidget {
@override
State createState() => _PopupMenuButtonDemo();
}
class _PopupMenuButtonDemo extends State {
@override
Widget build(BuildContext context) {
// TODO: implement build
return Scaffold(
appBar: AppBar(
actions: [_popMenu()],
),
body: Center(
child: RaisedButton(
child: Text(_selectedValue == null ? '未选择' : _selectedValue),
onPressed: () {
_showMenu(context);
},
),
),
);
}
String _selectedValue;
PopupMenuButton _popMenu() {
return PopupMenuButton(
itemBuilder: (context) => _getPopupMenu(context),
onSelected: (String value) {
print('onSelected');
_selectValueChange(value);
},
onCanceled: () {
print('onCanceled');
},
// child: RaisedButton(onPressed: (){},child: Text('选择'),),
icon: Icon(Icons.shopping_basket),
);
}
_selectValueChange(String value) {
setState(() {
_selectedValue = value;
});
}
_showMenu(BuildContext context) {
final RenderBox button = context.findRenderObject();
final RenderBox overlay = Overlay.of(context).context.findRenderObject();
final RelativeRect position = RelativeRect.fromRect(
Rect.fromPoints(
button.localToGlobal(Offset(0, 0), ancestor: overlay),
button.localToGlobal(button.size.bottomRight(Offset.zero),
ancestor: overlay),
),
Offset.zero & overlay.size,
);
var pop = _popMenu();
showMenu(
context: context,
items: pop.itemBuilder(context),
position: position,
).then((String newValue) {
if (!mounted) return null;
if (newValue == null) {
if (pop.onCanceled != null) pop.onCanceled();
return null;
}
if (pop.onSelected != null) pop.onSelected(newValue);
});
}
_getPopupMenu(BuildContext context) {
return >[
PopupMenuItem(
value: '语文',
child: Text('语文'),
),
PopupMenuItem(
value: '数学',
child: Text('数学'),
),
PopupMenuItem(
value: '英语',
child: Text('英语'),
),
PopupMenuItem(
value: '生物',
child: Text('生物'),
),
PopupMenuItem(
value: '化学',
child: Text('化学'),
),
];
}
}
如果你对Flutter还有疑问或者技术方面的疑惑,欢迎加入Flutter交流群(微信:laomengit)。
同时也欢迎关注我的Flutter公众号【老孟程序员】,公众号首发Flutter的相关内容。
Flutter地址:http://laomengit.com 里面包含160多个组件的详细用法。