Dart: Function

 14th December 2020 at 9:11am

基础语法

命名参数:

void enableFlags({bool bold, bool hidden}) {...}
enableFlags(bold: true, hidden: false);

必填命名参数:

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;
}

默认值

/// Sets the [bold] and [hidden] flags ...
void enableFlags({bool bold = false, bool hidden = false}) {...}

String say(String from, String msg,
    [String device = 'carrier pigeon']) {
  var result = '$from says $msg with a $device';
  return result;
}

集合类型也可以作为默认值,但是需要是 const(防止被修改):

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');
}

匿名函数

([[Type] param1[, …]]) {
  codeBlock;
};
var f1 = (int a, b) => a + b;
var f2 = (int a, b) {
    return a + b;
}