Elonas Marcauskas
Elonas Marcauskas

Reputation: 361

What is the correct way to use PopUpMenuItem onTap/onPessed in Flutter?

What is the correct way to call a function in Flutter when PopupMenuItem is tapped? Because inherently the widget does not have a onTapped property. The only thing close to it is setting the value of the PopupMenuItem widget. So the way I approached it is to set the state in the onSelected parameter in the PopupMenuButton. I did not find anyone talking about this situation on the internet so I thought it is worth to get opinions from other. Is this the proper way to do this?

I have tried to use a FlatButton as the child of the PopupMenuButton, but it did not work. It seemed that the application did not record the onTapped function of the FlatButton.

        PopupMenuButton<Choice>(
          onSelected: (Choice result) {
            setState(() {
              _selection = result;
              if (_selection == Choice.SIGN_OUT) {
                _signOut();
                print('[home.dart] _signOut()');
              }
            });
          },
          itemBuilder: (BuildContext context) => 
            <PopupMenuEntry<Choice>>[
            PopupMenuItem(
              child: Text(
                'Sign Out',
                style: TextStyle(color: Colors.black),
              ),
              value: Choice.SIGN_OUT,
            ),
          ],
        ),

The expected result is to call a function when a PopupMenuItem is tapped.

Upvotes: 3

Views: 1415

Answers (1)

Rahul
Rahul

Reputation: 51

PopUpMenuItem invocation can be done in two ways now.

We can do it with the onTap method now.

                  PopupMenuItem(
                    value: 'share',
                    onTap: () {
                      print("hello world");
                    },
                    child: Text('Share'),
                  ),

Or it can be done old school like the OP has mentioned.

                onSelected: (value) {
                  switch (value) {
                    case ('subscribe'):
                      print('Subscribing');
                      break;
                    case ('edit'):
                      print('editing');
                      break;
                    case ('share'):
                      print('sharing');
                      break;
                    default:
                      return;
                  }
                },

Upvotes: 1

Related Questions