'Flutter: await and then - baffling behavior
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?
Solution 1:[1]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Gazihan Alankus |
