Last active
December 1, 2022 18:05
-
-
Save ben-xD/be619b223f20656ad5833402f93487ad to your computer and use it in GitHub Desktop.
Solution: Example problem needing FutureOr<> in Dart
This file contains hidden or 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'; | |
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