函数定义

Function 类

  • 函数也是对象.
  1. bool isNoble(int atomicNumber) {
  2. return _nobleGases[atomicNumber] != null;
  3. }
  4. // 函数签名可以忽略返回值
  5. isNoble(atomicNumber) {
  6. return _nobleGases[atomicNumber] != null;
  7. }

函数体只有一行可以简写:

  1. bool isNoble(int atomicNumber) => _nobleGases[atomicNumber] != null;

参数

可选参数

可选参数可以是 named 或者 positional, 但不能都是.

Named 参数

  • {}
  1. // 定义
  2. /// Sets the [bold] and [hidden] flags ...
  3. void enableFlags({bool bold, bool hidden}) {...}
  4. // 调用
  5. // 也就是说 named 参数在传递时可以时随意位置
  6. enableFlags(bold: true, hidden: false);
  • 强制某个参数必须赋值
  1. // 使用 required 注解依赖 meta 包
  2. import package:meta/meta.dart
  3. const Scrollbar({Key key, @required Widget child})

Positional 参数

  • []
  1. // 定义
  2. String say(String from, String msg, [String device]) {
  3. var result = '$from says $msg';
  4. if (device != null) {
  5. result = '$result with a $device';
  6. }
  7. return result;
  8. }
  9. // 调用
  10. assert(say('Bob', 'Howdy') == 'Bob says Howdy');
  11. // 也就是说 positional 参数在传递时必须按照顺序
  12. assert(say('Bob', 'Howdy', 'smoke signal') ==
  13. 'Bob says Howdy with a smoke signal');

默认参数值

  • 参数值必须是编译时常量

为 named 参数指定默认值:

  1. /// Sets the [bold] and [hidden] flags ...
  2. void enableFlags({bool bold = false, bool hidden = false}) {...}
  3. // bold will be true; hidden will be false.
  4. enableFlags(bold: true);

为 positional 参数指定默认值:

  1. String say(String from, String msg,
  2. [String device = 'carrier pigeon', String mood]) {
  3. var result = '$from says $msg';
  4. if (device != null) {
  5. result = '$result with a $device';
  6. }
  7. if (mood != null) {
  8. result = '$result (in a $mood mood)';
  9. }
  10. return result;
  11. }
  12. assert(say('Bob', 'Howdy') ==
  13. 'Bob says Howdy with a carrier pigeon');

参数使用 list 或 map 默认值:

  1. void doStuff(
  2. {List<int> list = const [1, 2, 3],
  3. Map<String, String> gifts = const {
  4. 'first': 'paper',
  5. 'second': 'cotton',
  6. 'third': 'leather'
  7. }}) {
  8. print('list: $list');
  9. print('gifts: $gifts');
  10. }

main() 函数

  • main() 函数必须有
  • .. 被称为 cascade (级联)
  1. void main() {
  2. querySelector('#sample_text_id')
  3. ..text = 'Click me!'
  4. ..onClick.listen(reverseText);
  5. }
  • main() 函数可以有参数, 用于接收命令行参数
  1. // Run the app like this: dart args.dart 1 test
  2. void main(List<String> arguments) {
  3. print(arguments);
  4. assert(arguments.length == 2);
  5. assert(int.parse(arguments[0]) == 1);
  6. assert(arguments[1] == 'test');
  7. }

函数是一等对象

  • 函数可以作为参数传递给其它函数
  1. void printElement(int element) {
  2. print(element);
  3. }
  4. var list = [1, 2, 3];
  5. // Pass printElement as a parameter.
  6. list.forEach(printElement);
  • 给变量分配函数值
  1. var loudify = (msg) => '!!! ${msg.toUpperCase()} !!!';
  2. assert(loudify('hello') == '!!! HELLO !!!');

匿名函数

  • 定义匿名函数时, type 可以不写
  1. // 语法
  2. ([[Type] param1[, …]]) {
  3. codeBlock;
  4. };
  5. var list = ['apples', 'bananas', 'oranges'];
  6. list.forEach((item) {
  7. print('${list.indexOf(item)}: $item');
  8. });

词法范围

变量的范围是静态确定的.

  1. bool topLevel = true;
  2. void main() {
  3. var insideMain = true;
  4. void myFunction() {
  5. var insideFunction = true;
  6. void nestedFunction() {
  7. var insideNestedFunction = true;
  8. assert(topLevel);
  9. assert(insideMain);
  10. assert(insideFunction);
  11. assert(insideNestedFunction);
  12. }
  13. }
  14. }

词法闭包

  1. /// Returns a function that adds [addBy] to the
  2. /// function's argument.
  3. Function makeAdder(int addBy) {
  4. return (int i) => addBy + i;
  5. }
  6. void main() {
  7. // Create a function that adds 2.
  8. var add2 = makeAdder(2);
  9. // Create a function that adds 4.
  10. var add4 = makeAdder(4);
  11. assert(add2(3) == 5);
  12. assert(add4(3) == 7);
  13. }

测试函数是否相等

  1. void foo() {} // A top-level function
  2. class A {
  3. static void bar() {} // A static method
  4. void baz() {} // An instance method
  5. }
  6. void main() {
  7. var x;
  8. // Comparing top-level functions.
  9. x = foo;
  10. assert(foo == x);
  11. // Comparing static methods.
  12. x = A.bar;
  13. assert(A.bar == x);
  14. // Comparing instance methods.
  15. var v = A(); // Instance #1 of A
  16. var w = A(); // Instance #2 of A
  17. var y = w;
  18. x = w.baz;
  19. // These closures refer to the same instance (#2),
  20. // so they're equal.
  21. assert(y.baz == x);
  22. // These closures refer to different instances,
  23. // so they're unequal.
  24. assert(v.baz != w.baz);
  25. }

返回值

所有函数都有返回值, 如果在代码中没写 return, 那么 dart 自动在函数体最后加上 return null; .

  1. foo() {}
  2. assert(foo() == null);