1

我也是编码的新手。

我想做的事:

  • 要将抽屉菜单添加到 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'),
      ),
    );
  }
}

4

1 回答 1

1

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

于 2020-08-06T18:53:53.743 回答