:在Dart函数中有什么用? [英] What is the use of : in Dart function?

查看:89
本文介绍了:在Dart函数中有什么用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am testing some Flutter application and encounter : in a Dart Function, What is it used for?

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

I found it in Firebase for Flutter tutorial. I tried to search it in google, but can't find anything.

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

结果运行良好,我只想知道什么是:二手

The Result is working fine, i just want to know what is the : used for.

推荐答案

https://dart.dev/guides/language/language-tour ,构造函数部分:


  1. Superclass




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

Specify the superclass constructor after a colon (:), just before the constructor body (if any).



class Employee extends Person {
  Employee() : super.fromJson(getDefaultData());
  // ···
}




  1. 实例变量




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

Besides invoking a superclass constructor, you can also initialize instance variables before the constructor body runs. Separate initializers with commas.



// 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 -Method会做一些断言(在运行构造函数之前)并为变量 name赋值投票。由于这些变量是最终变量,因此必须在初始化记录实例之前对其进行分配!

So in your case the fromMap-Method does some assertions (before running the constructor) and assigns the variables name and vote. As these variables are final, they have to be assigned before initializing a record instance!

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

fromSnapshot just uses fromMap as super constructor.

这篇关于:在Dart函数中有什么用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆