Flutter PopupMenuItem onTap
The PopupMenuItem
widget in Flutter is used to display a menu item inside a popup menu. The onTap
property is a callback function that gets triggered when the menu item is tapped by the user. It allows you to perform certain actions or handle events when a particular menu item is selected.
Here is an example of how to use the PopupMenuItem
widget with the onTap
property:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
final List options = ['Option 1', 'Option 2', 'Option 3'];
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('PopupMenuItem onTap Example'),
),
body: Center(
child: RaisedButton(
child: Text('Open Popup Menu'),
onPressed: () {
_showPopupMenu(context);
},
),
),
),
);
}
void _showPopupMenu(BuildContext context) async {
String? selectedOption = await showDialog(
context: context,
builder: (BuildContext context) {
return PopupMenuButton(
itemBuilder: (BuildContext context) {
return options.map((String option) {
return PopupMenuItem(
value: option,
child: Text(option),
);
}).toList();
},
onSelected: (String value) {
Navigator.of(context).pop(value);
},
);
},
);
if (selectedOption != null) {
print('Selected option: $selectedOption');
}
}
}
In the above code, we create a `MyApp` widget as the root of our application. Inside the `build` method, we define the user interface using a `Scaffold` widget. We have an `AppBar` with a title and a `RaisedButton` at the center of the `body` section. The `RaisedButton` triggers the `_showPopupMenu` method when pressed.
The `_showPopupMenu` method is responsible for displaying the `PopupMenuButton`. It uses the `showDialog` function to display a modal dialog and returns the selected option using a `String?` future.
Inside the `builder` property of `showDialog`, we define the `PopupMenuButton` widget. The `itemBuilder` property is used to generate the list of menu items using the `options` list. The `onSelected` property is a callback function that gets triggered when a menu item is selected. In this example, we close the dialog and pass back the selected option using `Navigator.of(context).pop(value)`.
Finally, we have a check to print the selected option if it is not null. This can be modified to perform any desired actions based on the selected option.
When you run this example, a button will be displayed with the text “Open Popup Menu”. When you press the button, a popup menu will appear with three options. Selecting any option will print the selected option in the console.