Dart by Example: Optional Parameters

  1. // an ordered optional parameter
  2. String yell(String str, [bool exclaim = false]) {
  3. var result = str.toUpperCase();
  4. if (exclaim) result = result + '!!!';
  5. return result;
  6. }
  7. // named optional parameters
  8. String whisper(String str, {bool mysteriously: false}) {
  9. var result = str.toLowerCase();
  10. if (mysteriously) result = result + '...';
  11. return result;
  12. }
  13. main() {
  14. print(yell('Hello, World'));
  15. print(yell('Hello, World', true));
  16. print(whisper('Hello, World', mysteriously: true));
  17. }
  18.  
  1. $ dart optional_params.dart
  2. HELLO, WORLD
  3. HELLO, WORLD!!!
  4. hello, world...

by @jryanio | source | license