How to open a PopupMenuButton?

后端 未结 6 1743
暗喜
暗喜 2021-01-07 17:34

How do I open a popup menu from a second widget?

final button = new PopupMenuButton(
    itemBuilder: (_) => >[
                 


        
6条回答
  •  暖寄归人
    2021-01-07 18:16

    This works, but is inelegant (and has the same display problem as Rainer's solution above:

    class _MyHomePageState extends State {
      final GlobalKey _menuKey = new GlobalKey();
    
      @override
      Widget build(BuildContext context) {
        final button = new PopupMenuButton(
            key: _menuKey,
            itemBuilder: (_) => >[
                  new PopupMenuItem(
                      child: const Text('Doge'), value: 'Doge'),
                  new PopupMenuItem(
                      child: const Text('Lion'), value: 'Lion'),
                ],
            onSelected: (_) {});
    
        final tile =
            new ListTile(title: new Text('Doge or lion?'), trailing: button, onTap: () {
              // This is a hack because _PopupMenuButtonState is private.
              dynamic state = _menuKey.currentState;
              state.showButtonMenu();
            });
        return new Scaffold(
          body: new Center(
            child: tile,
          ),
        );
      }
    }
    

    I suspect what you're actually asking for is something like what is tracked by https://github.com/flutter/flutter/issues/254 or https://github.com/flutter/flutter/issues/8277 -- the ability to associated a label with a control and have the label be clickable -- and is a missing feature from the Flutter framework.

提交回复
热议问题