在 Flutter 中关闭后按抽屉

Rah*_*var 1 dart flutter

我正在向现有项目添加颤振。在颤振模块中,我的主页包含抽屉。但在背面按下时drawer未关闭。

@override
Widget build(BuildContext context) {
  return Scaffold(
    body: HomePage(),
    drawer: Drawer(),
  );
}
Run Code Online (Sandbox Code Playgroud)

Cop*_*oad 5

给Scaffold一个GlobalKey并包装你的小部件WillPopScope

GlobalKey<ScaffoldState> _globalKey = GlobalKey();
...

@override
Widget build(BuildContext context) {
  return Scaffold(
    key: _globalKey,
    drawer: Drawer(),
    body: WillPopScope(
      child: HomePage(),
      onWillPop: () {
        if (_globalKey.currentState.isDrawerOpen) {
          Navigator.pop(context); // closes the drawer if opened
          return Future.value(false); // won't exit the app
        } else {
          return Future.value(true); // exits the app
        }
      },
    ),
  );
}
Run Code Online (Sandbox Code Playgroud)