如何在异步函数中通过Navigator弹出特定路线



是否有方法将Navigator.pop()方法绑定到特定路由?

在我的例子中,Navigator.pop()是从小部件中的异步函数调用的,它需要一些时间才能完成,例如:

ElevatedButton(
onPressed: () async {
await doSomethingAsync();
if (mounted) {
Navigator.pop(context);
}
},
child: const Text("Do something async then pop")),
)

虽然该功能正在进行,但可能会发生以下情况:

  • 用户按下Android后退按钮可以提前弹出路线(类似于我之前提出的问题(
  • 用户可以通过执行另一个操作将另一个路由推到现有路由之上

在这两种情况下,我都希望导航器";领带;到显示小部件的特定路径,并且只有在还没有弹出的情况下才会弹出它。

最好的方法是什么?如果这不可能(或者过于复杂(,我也愿意使用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);
Navigator.pop(context);
}
},
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...'),
),
),
);
},
);
}

最新更新