首页 > 解决方案 > 从特定屏幕自动返回时如何关闭导航抽屉?

问题描述

我正在开发一个颤振项目,该项目有一个带有三个路线的导航抽屉。每当我前往特定路线并返回时,导航抽屉就会自动打开。我希望导航抽屉保持关闭状态,除非用户特别点击它。有什么办法可以做到这一点?

这是我的代码:

class NavList extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Drawer(
      child: ListView(
        padding: EdgeInsets.zero,
        children: <Widget>[
          UserAccountsDrawerHeader(
            decoration: BoxDecoration(
                image: DecorationImage(
              image: AssetImage('images/orange.png'),
              fit: BoxFit.cover,
            )),
            arrowColor: Colors.deepOrangeAccent[700],
            accountName: Text(''),
            accountEmail: Text(
              'username@gmail.com',
              style: TextStyle(
                fontWeight: FontWeight.bold,
                fontSize: 20.0,
              ),
            ),
            currentAccountPicture: CircleAvatar(
              radius: 22.0,
              backgroundColor: Colors.deepOrangeAccent[700],
              backgroundImage: AssetImage('images/profile.png'),
            ),
          ),
          ListItems(
            listTitle: 'Shops',
            listIcon: Icon(Icons.shop),
            listFunction: () {
              Navigator.pushNamed(context, ShopScreen.id);
            },
          ),
          ListItems(
            listTitle: 'Orders',
            listIcon: Icon(Icons.monetization_on),
            listFunction: () {
              Navigator.pushNamed(context, OrderScreen.id);
            },
          ),
          ListItems(
            listTitle: 'Logout',
            listIcon: Icon(Icons.logout),
            listFunction: () {
              Navigator.pushNamed(context, LoginScreen.id);
            },
          ),
        ],
      ),
    );
  }
}

I have refactored ListItems.

class ListItems extends StatelessWidget {
  ListItems({this.listTitle, this.listIcon, this.listFunction});
  final String listTitle;
  final Icon listIcon;
  final Function listFunction;

  @override
  Widget build(BuildContext context) {
    return ListTile(
      title: Text(listTitle),
      leading: IconButton(
        icon: listIcon,
        onPressed: () {
          
        },
      ),
      onTap: listFunction,
    );
  }
}

标签: flutterflutter-layoutflutter-navigationflutter-drawer

解决方案


有一些方法可以做到这一点:

onPressed:(){
   Navigator.pop(context);
   Navigator.pushNamed(context, ShopScreen.id);
 }

或使用导航器的 .then:

onPressed:(){
   Navigator.pushNamed(context, ShopScreen.id).then((val){
   Navigator.pop(context);
  });
 }

此外,您可以检查抽屉当前是否打开:

onPressed:(){
   Navigator.pushNamed(context, ShopScreen.id).then((val){
    if(Scaffold.of(context).isDrawerOpen){
     Navigator.pop(context);
     }
   });
  }

推荐阅读