How to use onTap or onPressed in PopupMenuItem
There is a property called onSelected
, you should use it, it handles onTap
event.
PopupMenuButton(
icon: Icon(Icons.settings),
onSelected: (newValue) { // add this property
setState(() {
_value = newValue; // it gives the value which is selected
});
},
itemBuilder: (context) => [
PopupMenuItem(
child: Text("Settings"),
value: 0,
),
PopupMenuItem(
child: Text("Flutter.io"),
value: 1,
),
PopupMenuItem(
child: Text("Google.com"),
value: 2,
),
],
)
Just add this to your PopupMenuButton:
onSelected: (result) {
if (result == 0) {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => SettingPage()),
);
}
},
And change your setting button to:
PopupMenuItem(
child: Text("Settings"),
value: 0,
),
I faced similar issues while navigating the screen using pop up menu button and I solve the issues by putting this method inside the onTap callback of PopupMenuItem:
onTap: (){
WidgetsBinding.instance!.addPostFrameCallback((_) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) {
return ScreenName();
},
),
);
});
}