在Flutter中按下后退按钮上的关闭导航抽屉

问题描述:

在我的第一个颤振应用程序中,我有一个材质设计好的导航抽屉.这项工作很好,但是我找不到任何方法可以关闭后退按钮上的导航抽屉,当使用 WillPopScope 显示 AlertDialog 时,如果打开了,请按一下.该应用程序仅显示 AlertDialog ,而不是在按下时关闭抽屉.我希望抽屉应该在已经打开的情况下关闭,否则显示 AlertDialog .

I have a material designed Navigation Drawer in my very first flutter app. This work's fine but I did't find any way to close the Navigation Drawer on Back Button Press if it's open when use WillPopScope to show AlertDialog. The application just show AlertDialog instead of close the Drawer when back press. I want Drawer should close if already open and show AlertDialog otherwise.

@override
Widget build(BuildContext context) {
  return WillPopScope(
    onWillPop: onBackPressed,
    child: Scaffold(
      appBar: AppBar(
        title: Text("Home"),
      ),
      drawer: Drawer(
      ),
      body: Center(
        child: Text("Home"),
      ),
    ),
  );
}

onBackPressed 显示关闭应用程序的对话框.

onBackPressed shows dialog to close the app.

Future<bool> onBackPressed() {
  return showDialog(
      barrierDismissible: false,
      context: context,
      builder: (context) => AlertDialog(
            title: Text("Do you want to exit?"),
            actions: <Widget>[
              FlatButton(
                  onPressed: () => Navigator.pop(context, false),
                  child: Text("No")),
              FlatButton(
                  onPressed: () => Navigator.pop(context, true),
                  child: Text("Yes"))
            ],
          ));
}

有人可以指导我如何实现这一目标吗?

Can anybody guide me how can I achieve this?

您可以在
下复制粘贴运行完整代码步骤1:您需要脚手架钥匙来控制抽屉,因此您需要 GlobalKey< ScaffoldState>._key = new GlobalKey< ScaffoldState>();
步骤2:在 onWillPop 中,您可以检查 isDrawerOpen 并执行 Navigator.pop

You can copy paste run full code below
Step 1: You need Scaffold key to controll Drawer so you need GlobalKey<ScaffoldState> _key = new GlobalKey<ScaffoldState>();
Step 2: In onWillPop You can check isDrawerOpen and do Navigator.pop

代码段

 GlobalKey<ScaffoldState> _key = new GlobalKey<ScaffoldState>();

  MyHomePage({Key key, this.title}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        if (_key.currentState.isDrawerOpen) {
          Navigator.of(context).pop();
          return false;
        }
        return true;
      },
      child: Scaffold(

工作演示

完整代码

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        print("My App Page");
        //return false;
      },
      child: MaterialApp(
        title: 'Flutter Demo',
        theme: ThemeData(
          primarySwatch: Colors.blue,
        ),
        home: MyHomePage(title: "test",),
      ),
    );
  }
}

class MyHomePage extends StatelessWidget {
  final String title;
  GlobalKey<ScaffoldState> _key = new GlobalKey<ScaffoldState>();

  MyHomePage({Key key, this.title}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        if (_key.currentState.isDrawerOpen) {
          Navigator.of(context).pop();
          return false;
        }
        return true;
      },
      child: Scaffold(
        key: _key,
        appBar: AppBar(title: Text(title)),
        body: Center(child: Text('My Page!')),
        drawer: Drawer(
          child: ListView(
            padding: EdgeInsets.zero,
            children: <Widget>[
              DrawerHeader(
                child: Text('Drawer Header'),
                decoration: BoxDecoration(
                  color: Colors.blue,
                ),
              ),
              ListTile(
                title: Text('page 2'),
                onTap: () {
                  Navigator.push(
                      context, new MaterialPageRoute(builder: (context) => Page2()));
                },
              ),
              ListTile(
                title: Text('Item 2'),
                onTap: () {
                  // Update the state of the app
                  // ...
                  // Then close the drawer
                  Navigator.pop(context);
                },
              ),
            ],
          ),
        ),
      ),
    );
  }
}


class Page2 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        print("Page2");
        _popNavigationWithResult(context, 'from_back');
        return false;
      },
      child: Scaffold(
        floatingActionButton: FloatingActionButton(
          onPressed: () {
            _popNavigationWithResult(context, 'from_button');
          },
        ),
        body: Container(
          child: Center(
            child: Text('Page 2',
                style: TextStyle(fontSize: 30.0, fontWeight: FontWeight.bold)),
          ),
        ),
      ),
    );
  }

  void _popNavigationWithResult(BuildContext context, dynamic result) {
    Navigator.pop(context, result);
  }
}