PopupMenu : Why does my widget not show up?

Dr_Skele·2022년 11월 22일
0

Flutter

목록 보기
4/19

While developing, I found a problem using PopupMenuButton. I wanted to push a new widget when tapping a PopupMenuItem. But somehow, nothing showed up. The Log showed the widget was pushed and there was no error message.

PopupMenuButton(
    itemBuilder: (context){
      return [
        PopupMenuItem(
          child: Text('edit'),
          onTap: () => 
            RouteNavigator().root.push(
              MaterialPageRoute(builder: (context) => NewWidget())
           ),
        ),
        PopupMenuItem(... ), ...
       ];
   },
)

Nothing seemed to be wrong with the code. Yeah it SEEMED to be. Apparently, there's a significant problem with this code.
You see, PopupMenuItem has some code hidden underneath. The onTap function calls the function you've provided, but also it pops the PopupMenuItem list widget and the pushed widget. I do not have any idea why it behaves like this, but I found a solution for it.

PopupMenuButton(
    itemBuilder: (context){
      return [
        PopupMenuItem(
          child: Text('edit'),
          onTap: () => Future(() =>
            RouteNavigator().root.push(
              MaterialPageRoute(builder: (context) => NewWidget())
            )
          ),
        ),
        PopupMenuItem(... ), ...
       ];
   },
)

Calling a Future does the trick. I suspect that the Future makes a call a frame later, and the widget is pushed when it's safe.

https://api.flutter.dev/flutter/material/PopupMenuButton-class.html

profile
Tireless And Restless Debugging In Source : TARDIS

0개의 댓글