2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

FlutterでPopupMenuを表示する

Last updated at Posted at 2021-03-28

Flutterで以下のようなPopupMenuを表示する方法を記す。

↓タップ

"Signed in as John Smith"の部分はただのラベル。選択不可。
"Sign out"の部分は、選択可。

実現のポイント

  • Menu全体には、PoupMenuButtonを使う
  • Menuの各項目にはPopupMenuItem、罫線にはPopupMenuDividerを使う
  • PoupMenuItemにenabled=falseを指定すると、選択不可項目を作れる
    • ただし、子Textがグレーアウトされるので、TextStyle#colorを指定する必要がある

コードサンプル

PopupMenuButton<MenuCommand>(
    onSelected: (MenuCommand value) {},
    // ボタンの見た目を指定。省略すると"..."になる。
    child: CircleAvatar(
        child: Icon(Icons.person),
    ),
    itemBuilder: (BuildContext context) => <PopupMenuEntry<MenuCommand>>[
      PopupMenuItem(
        enabled: false,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              'Signed in as',
              style: TextStyle(
                color: Colors.black87,
              ),
            ),
            Text(
              'John Smith',
              style: TextStyle(
                fontWeight: FontWeight.bold,
                color: Colors.black87,
              ),
            ),
          ],
        ),
      ),
      const PopupMenuDivider(),
      const PopupMenuItem(
        value: MenuCommand.signOut,
        child: Text('Sign out'),
      ),
    ],
  ),

MenuCommandは自分で定義したenumで、Menuの項目選択時のvalueの型に対応している。
サンプルコードでは定義を省略している。

最初に示した図のようにタイトルバーにボタンを置くなら、AppBar#actionsにPopupMenuButtonを於けばOK。

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?