如何在页面路由中使用浮动抽屉菜单?

时间:2020-08-06 15:47:36

标签: flutter flutter-drawer

我是新手,也可以进行编码。

我想做什么:

  • 要将抽屉式菜单添加到main.dart中,它将为菜单中的所有页面返回Scaffold。
  • 在每个页面中我想使用不同的支架。 (应用栏和正文)
我创建了页面,路线,抽屉;但是我无法在页面以及Builder(main.dart)中添加抽屉,我认为我有一些错误。

main.dart是这样的:

import 'package:flutter/material.dart';
import 'package:letter_app/screens/user/postbox.dart';
import 'package:letter_app/screens/user/unread.dart';

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

class MyApp extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return MyAppState();
  }
}

class MyAppState extends State<MyApp> {
  int selectedMenuItem = 0;
  final pageOptions = [
    PostBox(),
    Unread(),
  ];

  Widget buildDrawer(BuildContext context) {
    return Drawer(
      child: ListView(
        children: <Widget>[
          DrawerHeader(
            child: Text('Drawer Header'),
            decoration: BoxDecoration(),
          ),
          ListTile(
            title: Text('Unread'),
            onTap: () {
              Navigator.of(context)
                  .push(MaterialPageRoute(builder: (context) => new Unread()));
              Navigator.pop(context);
            },
          ),
          ListTile(
            title: Text('Post Box'),
            onTap: () {
              Navigator.of(context)
                  .push(MaterialPageRoute(builder: (context) => new PostBox()));
              Navigator.pop(context);
            },
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'New App',
      theme: ThemeData.dark(),
      routes: <String, WidgetBuilder>{
        '/screens/user/unread.dart': (BuildContext context) => Unread(),
        '/screens/user/postbox.dart': (BuildContext context) => PostBox(),
      },
      home: Builder(
        builder: (context) => Scaffold(
          drawer: buildDrawer(context),
          body: Container(child: pageOptions[selectedMenuItem]),
        ),
      ),
    );
  }
}

unread.dart是这样的:


import 'package:flutter/material.dart';

class Unread extends StatefulWidget {
  @override
  _UnreadState createState() => _UnreadState();
}

class _UnreadState extends State<Unread> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      drawer: ,
      appBar: AppBar(
        title: Text('Welcome to Flutter'),
      ),
      body: Center(
        child: Text('Unread'),
      ),
    );
  }
}

1 个答案:

答案 0 :(得分:0)

只需在单独的dart文件中定义buildDrawer小部件,然后导入文件即可。然后,将其分配给每个脚手架。