Skip to content

Instantly share code, notes, and snippets.

@s0nerik
Last active September 27, 2023 09:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save s0nerik/cc4d28e6ced5f4c3a65f6c149492d67d to your computer and use it in GitHub Desktop.
Save s0nerik/cc4d28e6ced5f4c3a65f6c149492d67d to your computer and use it in GitHub Desktop.
(Dart) FutureOr handling differences

(Dart) FutureOr handling differences

Created with <3 with dartpad.dev.

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