简体   繁体   English

Flutter 如何在 PopupMenuButton 小部件中获取上下文?

[英]Flutter how i can get context in PopupMenuButton widget?

I have a PopupMenuButton.我有一个 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 .未定义的名称context How can I get the context in Navigator.push ?如何在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.您需要将BuildContext传递给您的_childPopup function。 You likely defined this function in a place where BuildContext is not directly available.您可能在BuildContext不直接可用的地方定义了这个 function。 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.这样做可确保BuildContext可用于 function 并允许您更好地控制它将使用哪个上下文。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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