在Flutter的背面关闭抽屉

问题描述 投票:0回答:1

我正在为现有项目增添动力。在颤动模块中我有它包含抽屉的主页。但在背面按drawer没有关闭。

@override
Widget build(BuildContext context) {
  return Scaffold(
    body: HomePage(),
    drawer: Drawer(),
  );
}
dart flutter
1个回答
0
投票

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
        }
      },
    ),
  );
}
© www.soinside.com 2019 - 2024. All rights reserved.