首页 > 解决方案 > 如何在保持对话框打开的同时关闭抽屉?

问题描述

最小代码:

void main() => runApp(MaterialApp(home: MainPage()));

class MainPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      drawer: MyDrawer(),
    );
  }
}

class MyDrawer extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Drawer(
      child: RaisedButton(
        onPressed: () {
          // Close the Drawer, not the Dialog. 
          Timer(Duration(seconds: 2), () => Navigator.of(context, rootNavigator: true).pop());

          // Show the Dialog and keep it in opened state. 
          showDialog(
            context: context,
            builder: (_) => AlertDialog(title: Text('FooDialog')),
          );
        },
        child: Text('Show Dialog'),
      ),
    );
  }
}

按下按钮时,我正在显示对话框,2 秒后我想关闭对话框,Drawer同时保持Dialog在屏幕上打开。Timer为此,我正在使用rootNavigator. Navigator但是,我的对话被解雇了。

GlobalKey<DrawerControllerState>除了使用东西之外,还有什么办法可以关闭抽屉吗?

标签: flutter

解决方案


class MyDrawer extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Drawer(
      child: RaisedButton(
        onPressed: () {
          // Close the Drawer, not the Dialog. 
          Timer(Duration(seconds: 2), () => Scaffold.of(context).openEndDrawer());

          // Show the Dialog and keep it in opened state. 
          showDialog(
            context: context,
            builder: (_) => AlertDialog(title: Text('FooDialog')),
          );
        },
       child: Text('Show Dialog'),
     ),
   );
  }
}

推荐阅读