Flutter:等待然后 - 令人困惑的行为
ImagePicker _picker = ImagePicker(); // from image_picker.dart
try {
XFile? pickedFile = await _picker.pickImage(source: source);
do xyz;
}
catch (e){
...something
}
vs
try {
_picker.pickImage(source: source).then((file) {do xyz;});
}
catch (e){
...something
}
文件选择对话框打开。如果我在没有选择文件的情况下取消,则行为如下:
情况 1:await - 'do xyz' 或 catch 块均未执行 - 函数仅返回
情况 2:then - 执行 'do xyz' 块
发生了什么在?
ImagePicker _picker = ImagePicker(); // from image_picker.dart
try {
XFile? pickedFile = await _picker.pickImage(source: source);
do xyz;
}
catch (e){
...something
}
vs
try {
_picker.pickImage(source: source).then((file) {do xyz;});
}
catch (e){
...something
}
The file select dialog opens. If I cancel without selecting a file, this is the behavior:
Case 1: await - neither 'do xyz' or the catch block is executed - the function just returns
case 2: then - the 'do xyz' block is executed
What is going on?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你所声称的是不可能的。如果在第二个示例中执行,第一个示例中的
do xyz
行也会执行。它只会稍后执行。这两个示例非常相似,但有一个区别:第二个示例的 try/catch 不捕获此处的异步错误。要解决此问题并使两个示例完全相同,您需要向第二个示例添加
await
。现在这两个是完全相同的:因为否则您启动一个异步作业但不等待它,执行会立即脱离 try/catch,并且无法捕获稍后发生的错误。
What you claim is just not possible. The
do xyz
line in the first example will execute if it executes in the second example. It will just execute a bit later in time.These two examples are quite similar but there is one difference: the second one's try/catch does not catch the async errors here. To fix that and to make the two examples exactly the same, you need to add an
await
to the second one. Now these two are exactly the same:Because otherwise you initiate an async job but not await it, the execution gets out of the try/catch immediately and it cannot catch errors that will happen later.