Flutter menuBar: how to remove background/border?

272 Views Asked by At

Flutter menuBar: how to remove background/border?

MenuBar(children: [
   MenuItemButton(child: Text('Login')),
   MenuItemButton(child: Text('Register')),
])

--------------------
| Login  Register  |
--------------------

How to remove background (to be transparent) and border?

Login  Register
1

There are 1 best solutions below

4
Alberto Fecchi On BEST ANSWER

You can use style property and MenuStyle class (https://api.flutter.dev/flutter/material/MenuStyle-class.html):

elevation should be set to 0 (otherwise, with a Color.transparent, you'll see the widget's shadow).

MenuBar(
  style: MenuStyle(
    backgroundColor: MaterialStatePropertyAll<Color>(Colors.transparent),
    elevation: MaterialStatePropertyAll<double>(0),
    shape: MaterialStatePropertyAll<ContinuousRectangleBorder>(ContinuousRectangleBorder())
  ),
  children: ...,
)

Here's a full example. Changing backgroundColor property of Scaffold will demonstrate that MenuBar is effectively transparent, shadowless and with rectangular borders:

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      title: 'MenuBar Demo',
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key});

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.red,
      body: SafeArea(
        child: Column(
          children: [
            Row(
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                Expanded(
                  child: MenuBar(
                      style: const MenuStyle(
                          backgroundColor: MaterialStatePropertyAll<Color>(
                              Colors.transparent),
                          elevation: MaterialStatePropertyAll<double>(0),
                          shape: MaterialStatePropertyAll<
                              ContinuousRectangleBorder>(
                              ContinuousRectangleBorder())),
                      children: [
                        SubmenuButton(menuChildren: [
                          MenuItemButton(
                              onPressed: () {},
                              child: const MenuAcceleratorLabel('Test'))
                        ], child: const MenuAcceleratorLabel('File'))
                      ]),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}