:在Dart函数中有什么用?

时间:2019-06-16 09:49:44

标签: function flutter dart

我正在测试一些Flutter应用程序并遇到:在Dart Function中,它是做什么用的?

我在Firebase for Flutter教程中找到了它。我试图在Google中进行搜索,但找不到任何内容。

class Record {
  final String name;
  final int votes;
  final DocumentReference reference;

  Record.fromMap(Map<String, dynamic> map, {this.reference})
      : assert(map['name'] != null),
        assert(map['votes'] != null),
        name = map['name'],
        votes = map['votes'];

  Record.fromSnapshot(DocumentSnapshot snapshot)
      : this.fromMap(snapshot.data, reference: snapshot.reference);

  @override
  String toString() => "Record<$name:$votes>";
}

结果运行良好,我只想知道它的用途。

1 个答案:

答案 0 :(得分:1)

https://dart.dev/guides/language/language-tour的“构造方法”部分开始

  1. 超类
  

在冒号(:)之后,就在构造函数主体(如果有)之前指定超类构造函数。

class Employee extends Person {
  Employee() : super.fromJson(getDefaultData());
  // ···
}
  1. 实例变量
  

除了调用超类构造函数外,还可以在构造函数主体运行之前初始化实例变量。用逗号分隔初始化程序。

// Initializer list sets instance variables before
// the constructor body runs.
Point.fromJson(Map<String, num> json)
    : x = json['x'],
      y = json['y'] {
  print('In Point.fromJson(): ($x, $y)');
}

您的示例:

因此,在您的情况下,fromMap-方法会执行一些声明(在运行构造函数之前),并分配变量namevote。由于这些变量是最终变量,因此必须在初始化记录实例之前对其进行分配!

fromSnapshot仅使用fromMap作为超级构造函数。