Skip to content

Instantly share code, notes, and snippets.

@ben-xD
Last active December 1, 2022 18:05
Show Gist options
  • Save ben-xD/be619b223f20656ad5833402f93487ad to your computer and use it in GitHub Desktop.
Save ben-xD/be619b223f20656ad5833402f93487ad to your computer and use it in GitHub Desktop.
Solution: Example problem needing FutureOr<> in Dart
import 'dart:async';
String callbackOne() => "hello";
Future<String> callbackTwo() async => (await Future.delayed(Duration(seconds: 1),() => "This is a sentence"));
Future<int> getLengthOfResult(FutureOr<String> Function() callback) async {
// I can await on callbackOne, even though it returns a String.
final result = await callback();
return result.length;
}
Future<int> getLengthOfResult2(String Function() callback) async {
return callback().length;
}
main() async {
print("Length of callbackOne result: ${await getLengthOfResult(callbackOne)}");
print("Length of callbackTwo result: ${await getLengthOfResult(callbackTwo)}");
}
// Solution for https://dartpad.dev/?id=0e12aa0f4745213a7efa5b5ff8c4934e
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment