从特定屏幕自动返回时,如何关闭导航抽屉



我正在做一个flutter项目,该项目有一个带有三条路线的导航抽屉。每当我走到一条特定的路线并回来时,导航抽屉就会自动打开。我希望导航抽屉保持关闭,直到用户特别点击它。有什么方法可以做到这一点吗?

这是我的代码:

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,
);
}
}

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

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

或者使用导航器:

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);
}
});
}

我还没有测试过。也许这可能工作

onPressed: () async {
await Navigator.pushNamed(
context, "Screen").then((value) =>
Scaffold.of(context).openEndDrawer());
},

这可能有助于

onPressed: () {
Navigator.pop(context);
Navigator.of(context).pushNamed('/settings');
}

最新更新