简体   繁体   中英

Flutter how i can get context in PopupMenuButton widget?

I have a PopupMenuButton. But if I want to call a method that will jump to another page

Navigator.push(context,MaterialPageRoute(builder: (context) => SingleOrder()),);

I have an error. Undefined name context . How can I get the context in Navigator.push ?

Widget _childPopup() => PopupMenuButton<int>(

 onSelected: (result) {
  if (result == 0) {
  Navigator.push(
    context,
    MaterialPageRoute(builder: (context) => SingleOrder()),
   );
 }
},

itemBuilder: (context) => [
  PopupMenuItem(
   value: 0,
    child: Text(
    "MENU 1",
    style: TextStyle(
        color: Colors.black54),
  ),
),
PopupMenuItem(
  value: 1,
  child: Text(
    "MENU 2",
    style: TextStyle(
        color:  Colors.black54),
    ),
  ),
],
);

You need to pass BuildContext to your _childPopup function. You likely defined this function in a place where BuildContext is not directly available. Ex.

Widget _childPopup(BuildContext context) => PopupMenuButton<int>(

 onSelected: (result) {
  if (result == 0) {
  Navigator.push(
    context,
    MaterialPageRoute(builder: (context) => SingleOrder()),
   );
 }
},

itemBuilder: (context) => [
  PopupMenuItem(
   value: 0,
    child: Text(
    "MENU 1",
    style: TextStyle(
        color: Colors.black54),
  ),
),
PopupMenuItem(
  value: 1,
  child: Text(
    "MENU 2",
    style: TextStyle(
        color:  Colors.black54),
    ),
  ),
],
);

Doing this ensures that BuildContext will be available to the function and allows you to better control which context it will use.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM