如何在 flutter 的应用栏中添加抽屉?

How can I add a drawer in the app bar in flutter?

我想在我的应用栏中添加一个抽屉,但我无法修复它。 我的代码是这样的,请帮忙!

Widget appBarMain(BuildContext context) {
  return AppBar(
    centerTitle: false,
    title: Image.asset(
      'assets/images/logox.png',
      height: 45,
    ),
    flexibleSpace: Container(
      decoration: BoxDecoration(
        gradient: LinearGradient(
            begin: Alignment.topLeft,
            end: Alignment.bottomRight,
            colors: <Color>[Colors.pink[400], Colors.blue[400]]),
      ),
    ),
  );
}

阅读https://flutter.dev/docs/cookbook/design/drawer

这样做

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData.dark().copyWith(scaffoldBackgroundColor: darkBlue),
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        appBar: appBarMain(context),  // => appbar is an attribute in Scaffold
        body: Center(
          child: MyWidget(),
        ),
      ),
    );
  }
}

抽屉被添加到 Scaffold 而不是 AppBar。 AppBar中自动显示的只是它的图标。

参见:https://flutter.dev/docs/cookbook/design/drawer

添加带脚手架的抽屉:

return Scaffold(
      appBar: appBarMain(context),
      body: Center(child: Text('My Page!')),
      drawer: Drawer(
        // Add a ListView to the drawer. This ensures the user can scroll
        // through the options in the drawer if there isn't enough vertical
        // space to fit everything.
        child: ListView(
          // Important: Remove any padding from the ListView.
          padding: EdgeInsets.zero,
          children: <Widget>[
            DrawerHeader(
              child: Text('Drawer Header'),
              decoration: BoxDecoration(
                color: Colors.blue,
              ),
            ),
            ListTile(
              title: Text('Item 1'),
              onTap: () {
                // Update the state of the app
                // ...
                // Then close the drawer
                Navigator.pop(context);
              },
            ),
            ListTile(
              title: Text('Item 2'),
              onTap: () {
                // Update the state of the app
                // ...
                // Then close the drawer
                Navigator.pop(context);
              },
            ),
          ],
        ),
      ),
    );