Created
January 24, 2020 17:26
-
-
Save AlexVegner/ba1949cb30ecd8780ac9382eedd18669 to your computer and use it in GitHub Desktop.
dart_future.dart
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'dart:async'; | |
main() async { | |
//final version = -1; | |
//final version = 0; | |
final version = 1; | |
// use then / catchError | |
print('handle with then-catchError'); | |
checkVersion(version) | |
.then((o) { | |
print('future done'); | |
}) | |
.catchError((e) => print('future format error $e'), | |
test: (e) => e is FormatException) | |
.catchError((e) { | |
print('future $e'); | |
}) | |
.whenComplete(() => print('future complete')); | |
// use try catch | |
print('\nhandle with try-catch'); | |
try { | |
await checkVersion(version); | |
print('try-catch done'); | |
} on FormatException catch (e) { | |
print('try-catch format error $e'); | |
} catch (e) { | |
print('try-catch error $e'); | |
} finally { | |
print('try-catch finally'); | |
} | |
print(await someFutureResult()); | |
print('Exit'); | |
} | |
Future checkVersion(int value) async { | |
await Future.delayed(Duration(seconds: 1)); | |
if (value == 0) { | |
throw 'error'; | |
} else if (value == -1) { | |
throw FormatException(); | |
} | |
return value; | |
} | |
/// Sometimes we need to have Completer for async operation | |
Future<dynamic> someFutureResult(){ | |
final c = new Completer(); | |
// complete will be called in 3 seconds by the timer. | |
Timer(Duration(seconds: 3), () { | |
print("Yeah, this line is printed after 3 seconds"); | |
c.complete("you should see me final"); | |
}); | |
return c.future; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment