Flutter:等待然后 - 令人困惑的行为

发布于 2025-01-11 00:28:30 字数 488 浏览 0 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

猛虎独行 2025-01-18 00:28:30

你所声称的是不可能的。如果在第二个示例中执行,第一个示例中的 do xyz 行也会执行。它只会稍后执行。

这两个示例非常相似,但有一个区别:第二个示例的 try/catch 不捕获此处的异步错误。要解决此问题并使两个示例完全相同,您需要向第二个示例添加 await。现在这两个是完全相同的:

try {
      XFile? pickedFile = await _picker.pickImage(source: source);
      do xyz;
}
catch (e){
      ...something
}
try {
      await _picker.pickImage(source: source).then((file) {do xyz;});
}
catch (e){
      ...something
}

因为否则您启动一个异步作业但不等待它,执行会立即脱离 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:

try {
      XFile? pickedFile = await _picker.pickImage(source: source);
      do xyz;
}
catch (e){
      ...something
}
try {
      await _picker.pickImage(source: source).then((file) {do xyz;});
}
catch (e){
      ...something
}

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文