Search code examples
flutterappbar

Flutter appBar: how to make appBar overflow to popup menu?


Flutter appBar:

 Scaffold(
   appBar : AppBar(
      actions: [IconButton1 IconButton2 ... IconButtonN]
   ), 
   body:
 );


 IconButton1 IconButton2 ... IconButtonN

In a narrow screen, the list of icon buttons will overflow. How to make the list of overflowed buttons into a popup menu automatically?

 IconButton1 IconButton2 PopupMenuButton
                         Item1
                         Item2
                          ...
                         ItemN

Solution

  • You can use MediaQuery.of(context).size.width to get the device width and conditionally render the icon buttons directly, or create a PopupMenuButton that displays the icon buttons in a popup menu.

    Like this:

    import 'package:flutter/material.dart';
    
    class IconButtonsScreen extends StatelessWidget {
      final List<IconButton> iconButtons = [
        IconButton(icon: Icon(Icons.home), onPressed: () {}),
        IconButton(icon: Icon(Icons.search), onPressed: () {}),
        // ... add more icon buttons
      ];
    
      @override
      Widget build(BuildContext context) {
        final screenWidth = MediaQuery.of(context).size.width;
    
        return Scaffold(
          appBar: AppBar(
            title: Text('Icon Buttons'),
          ),
          body: Row(
            children: [
              if (screenWidth > 600) // Set your desired breakpoint
                ...iconButtons,
              if (screenWidth <= 600)
                PopupMenuButton<String>(
                  icon: Icon(Icons.more_vert),
                  itemBuilder: (BuildContext context) {
                    return iconButtons.map((IconButton button) {
                      return PopupMenuItem<String>(
                        value: 'menuItem',
                        child: button.icon,
                      );
                    }).toList();
                  },
                ),
            ],
          ),
        );
      }
    }