Created with <3 with dartpad.dev.
Last active
September 26, 2022 03:51
-
-
Save maks/7932a519d283b2f2e4796e6bea5e6e2d to your computer and use it in GitHub Desktop.
popup menu example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:flutter/material.dart'; | |
// example code from: https://stackoverflow.com/a/70236525/85472 | |
// This is the type used by the popup menu below. | |
enum Menu { itemOne, itemTwo, itemThree, itemFour } | |
void main() => runApp(const MyApp()); | |
class MyApp extends StatelessWidget { | |
const MyApp({super.key}); | |
static const String _title = 'Flutter Code Sample'; | |
@override | |
Widget build(BuildContext context) { | |
return const MaterialApp( | |
title: _title, | |
home: MyStatefulWidget(), | |
); | |
} | |
} | |
class MyStatefulWidget extends StatefulWidget { | |
const MyStatefulWidget({super.key}); | |
@override | |
State<MyStatefulWidget> createState() => _MyStatefulWidgetState(); | |
} | |
class _MyStatefulWidgetState extends State<MyStatefulWidget> { | |
String _selectedMenu = ''; | |
@override | |
Widget build(BuildContext context) { | |
final _accKey = GlobalKey(); | |
return Scaffold( | |
body: Center( | |
child: MaterialButton( | |
key: _accKey, | |
child: Text("Account"), | |
onPressed: () { | |
final RenderBox renderBox = | |
_accKey.currentContext?.findRenderObject() as RenderBox; | |
final Size size = renderBox.size; | |
final Offset offset = renderBox.localToGlobal(Offset.zero); | |
showMenu( | |
context: context, | |
position: RelativeRect.fromLTRB( | |
offset.dx, | |
offset.dy + size.height, | |
offset.dx + size.width, | |
offset.dy + size.height), | |
items: [ | |
PopupMenuItem<String>( | |
onTap: () => print("MENU1 selected"), | |
child: const Text('menu option 1'), value: '1'), | |
PopupMenuItem<String>( | |
onTap: () => print("MENU2 selected"), | |
child: const Text('menu option 2'), value: '2'), | |
PopupMenuItem<String>( | |
onTap: () => print("MENU3 selected"), | |
child: const Text('menu option 3'), value: '3'), | |
]); | |
}), | |
), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment