有没有办法将
Navigator.pop()
方法绑定或绑定到特定路线?
在我的例子中,
Navigator.pop()
是从小部件中的异步函数调用的,这需要一些时间才能完成,例如:
ElevatedButton(
onPressed: () async {
await doSomethingAsync();
if (mounted) {
Navigator.pop(context);
}
},
child: const Text("Do something async then pop")),
)
虽然该功能正在进行中,但可能会发生以下情况:
在这两种情况下,我都希望导航器“绑定”到显示小部件的特定路径,并且仅在尚未弹出时才将其弹出。
最好的方法是什么?如果这是不可能的(或过于复杂),我也愿意接受使用 go_router 包的解决方案,同样的问题也适用。
你最好像这样使用它
asyncFunction().then((value){
Navigator.pop(context);
});
确保在 asyncFunction 完成之前它不会导航, 并确保 asyncFunction 是一个 Future 函数
Future<someThing> asyncFunction()async
{
someLogic;
}
您可以在 Future 运行时显示加载对话框。它还有助于让用户知道应用程序正在处理某些事情。
ElevatedButton(
onPressed: () async {
showMyWaitingDialog(context);
await doSomethingAsync();
if (mounted) {
Navigator.pop(context); // will dismiss waiting dialog
Navigator.pop(context); // will close current screen/page
}
},
child: const Text('Do something async then pop'),
)
其他地方的对话框:
showMyWaitingDialog(BuildContext context) {
showDialog(
context: context,
barrierDismissible: false,
builder: (_) {
return const AlertDialog(
content: SizedBox(
height: 60,
child: Center(
child: Text('Waiting for...'),
),
),
);
},
);
}