Dart语言学习笔记(2)

函数

// 函数
bool isNoble(int atomicNumber) {
  return _nobleGases[atomicNumber] != null;
}
// 返回类型可省略(不推荐)
isNoble(atomicNumber) {
  return _nobleGases[atomicNumber] != null;
}
// 函数只包含一个表达式时可使用缩略语法
//  => expr 相当于 { return expr; }
bool isNoble(int atomicNumber) => _nobleGases[atomicNumber] != null;

必要参数和可选参数

必要参数在前,可选参数在后
可选参数可以是 具名参数或位置参数

// 具名实参 paramName: value
enableFlags(bold: true, hidden: false);
// 具名形参 {param1, param2, …}
/// Sets the [bold] and [hidden] flags ...
void enableFlags({bool bold, bool hidden}) {...}
// 可选参数中也可标注必要参数
import package:meta/meta.dart
const Scrollbar({Key key, @required Widget child})
// 位置参数
String say(String from, String msg, [String device]) {
  var result = '$from says $msg';
  if (device != null) {
    result = '$result with a $device';
  }
  return result;
}
// 调用位置参数
assert(say('Bob', 'Howdy') == 'Bob says Howdy');
assert(say('Bob', 'Howdy', 'smoke signal') ==
    'Bob says Howdy with a smoke signal');
// 缺省参数
/// Sets the [bold] and [hidden] flags ...
void enableFlags({bool bold = false, bool hidden = false}) {...}
// bold will be true; hidden will be false.
enableFlags(bold: true);
// 使用缺省参数
String say(String from, String msg,
    [String device = 'carrier pigeon', String mood]) {
  var result = '$from says $msg';
  if (device != null) {
    result = '$result with a $device';
  }
  if (mood != null) {
    result = '$result (in a $mood mood)';
  }
  return result;
}
assert(say('Bob', 'Howdy') ==
    'Bob says Howdy with a carrier pigeon');
// 缺省参数也可以是 List 或 Map
void doStuff(
    {List<int> list = const [1, 2, 3],
    Map<String, String> gifts = const {
      'first': 'paper',
      'second': 'cotton',
      'third': 'leather'
    }}) {
  print('list:  $list');
  print('gifts: $gifts');
}

main 函数

main 函数为程序的起点,返回 void,有一个可选的 List<String> 类型的参数

void main() {
  querySelector('#sample_text_id')
    ..text = 'Click me!'
    ..onClick.listen(reverseText);
}
// Run the app like this: dart args.dart 1 test
void main(List<String> arguments) {
  print(arguments);
  assert(arguments.length == 2);
  assert(int.parse(arguments[0]) == 1);
  assert(arguments[1] == 'test');
}

函数是一等公民

// 将函数作为参数传给另一个函数
void printElement(int element) {
  print(element);
}
var list = [1, 2, 3];
// Pass printElement as a parameter.
list.forEach(printElement);
// 将函数赋值给变量
// loudify 的类型是 String Function(String)
var loudify = (msg) => '!!! ${msg.toUpperCase()} !!!';
assert(loudify('hello') == '!!! HELLO !!!');

匿名函数

匿名函数的语法

([[Type] param1[, …]]) {
  codeBlock;
};
var list = ['apples', 'bananas', 'oranges'];
list.forEach((item) {
  print('${list.indexOf(item)}: $item');
});
// 缩略语法
list.forEach(
    (item) => print('${list.indexOf(item)}: $item'));

其他

// 变量的作用域
bool topLevel = true;
void main() {
  var insideMain = true;
  void myFunction() {
    var insideFunction = true;
    void nestedFunction() {
      var insideNestedFunction = true;
      assert(topLevel);
      assert(insideMain);
      assert(insideFunction);
      assert(insideNestedFunction);
    }
  }
}
// 闭包
/// Returns a function that adds [addBy] to the
/// function's argument.
Function makeAdder(int addBy) {
  return (int i) => addBy + i;
}
void main() {
  // Create a function that adds 2.
  var add2 = makeAdder(2);
  // Create a function that adds 4.
  var add4 = makeAdder(4);
  assert(add2(3) == 5);
  assert(add4(3) == 7);
}
// 函数间的比较(测试是否相等)
void foo() {} // A top-level function
class A {
  static void bar() {} // A static method
  void baz() {} // An instance method
}
void main() {
  var x;
  // Comparing top-level functions.
  x = foo;
  assert(foo == x);
  // Comparing static methods.
  x = A.bar;
  assert(A.bar == x);
  // Comparing instance methods.
  var v = A(); // Instance #1 of A
  var w = A(); // Instance #2 of A
  var y = w;
  x = w.baz;
  // These closures refer to the same instance (#2),
  // so they're equal.
  assert(y.baz == x);
  // These closures refer to different instances,
  // so they're unequal.
  assert(v.baz != w.baz);
}
// 没有返回值的函数返回 null
foo() {}
assert(foo() == null);
原文地址:https://www.cnblogs.com/zwvista/p/13665650.html