Home > Net >  PopupMenuButton that looks like ElevatedButton in flutter
PopupMenuButton that looks like ElevatedButton in flutter

Time:08-01

I'm a beginer of flutter and trying to write a code to display a button that looks like ElevatedButton and displays popup when it is tapped. I wrote a code like below but didn't work. Does anyone know how to solve this problem?

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Welcome to Flutter',
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Welcome to Flutter'),
        ),
        body: Center(
            child: PopupMenuButton(
                itemBuilder: (context) => [
                      PopupMenuItem(
                          child: Column(
                              children: const [Text('item1'), Text('item2')]))
                    ],
                child: ElevatedButton(
                  onPressed: () {},
                  child: const Text('show popup menu'),
                ))),
      ),
    );
  }
}

CodePudding user response:

Do this:

/*...*/
ElevatedButton(
  onPressed: () {
    showDialog(
      context: context,
      builder: (BuildContext context) => SimpleDialog(content: Container(),),
    );
  },
  child: const Text('show popup menu'),
)
// then customize the SimpleDialog

For more info check the docs.

CodePudding user response:

It's possible to show the popup menu programmatically by calling PopupMenuButtonState.showButtonMenu(). And to get a reference to PopupMenuButtonState use a GlobalKey.

The code is going to be like this:

class MyApp extends StatelessWidget {
  MyApp({Key? key}) : super(key: key);

  final _popupMenu = GlobalKey<PopupMenuButtonState>();    // <- Here

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        body: Center(
          child: PopupMenuButton(
            key: _popupMenu,                               // <- Here
            itemBuilder: (context) => [
              PopupMenuItem(
                  child: Column(children: const [Text('item1'), Text('item2')]))
            ],
            child: ElevatedButton(
              onPressed: () {
                _popupMenu.currentState?.showButtonMenu(); // <- Here
              },
              child: const Text('show popup menu'),
            ),
          ),
        ),
      ),
    );
  }
}
  • Related