Created with <3 with dartpad.dev.
Last active
September 27, 2023 09:07
-
-
Save s0nerik/cc4d28e6ced5f4c3a65f6c149492d67d to your computer and use it in GitHub Desktop.
(Dart) FutureOr handling differences
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'; | |
/// Produces the following output (since [futureOrResult] value is available synchronously): | |
/// ``` | |
/// process: 0 | |
/// result: 0 | |
/// process: 1 | |
/// ``` | |
Future<void> main() async { | |
unawaited(process()); | |
final futureOrResult = x(); | |
if (futureOrResult is Future) { | |
final result = await futureOrResult; | |
print('result: $result'); | |
} else { | |
print('result: $futureOrResult'); | |
} | |
} | |
/// Rename this to `main` to see a difference in behavior. | |
/// | |
/// Produces the following output (since [futureOrResult] value is available only asynchronously): | |
/// ``` | |
/// process: 0 | |
/// process: 1 | |
/// result: 0 | |
/// ``` | |
Future<void> _main() async { | |
unawaited(process()); | |
final result = await x(); | |
print('result: $result'); | |
} | |
Future<void> process() async { | |
print('process: 0'); | |
await Future.value(); | |
print('process: 1'); | |
} | |
FutureOr<int> x() { | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment