gpt4 book ai didi

flutter - 命名为 ":"的构造函数

转载 作者:行者123 更新时间:2023-12-03 03:58:06 24 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Colon : in Dart constructor syntax

(2 个回答)


1年前关闭。




我正在通过 Firebase 查找 flutter 文档并找到了这一行,我不知道为什么使用“:”这个符号,我是 dart 的新手

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

为什么我不能像这样初始化

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

代码实验室链接 https://codelabs.developers.google.com/codelabs/flutter-firebase/#4

断言函数有什么作用?

最佳答案

它被称为初始化列表,它是调用构造函数时调用的第一件事。

来自 docs

Initializer list

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

Warning: The right-hand side of an initializer does not have access to this.

During development, you can validate inputs by using assert in the initializer list.


Point.withAssert(this.x, this.y) : assert(x >= 0) {
print('In Point.withAssert(): ($x, $y)');
}

Initializer lists are handy when setting up final fields. The following example initializes three final fields in an initializer list. Click Run to execute the code.


class Point {
final num x;
final num y;
final num distanceFromOrigin;

Point(x, y)
: x = x,
y = y,
distanceFromOrigin = sqrt(x * x + y * y);
}

Redirecting constructors

Sometimes a constructor’s only purpose is to redirect to another constructor in the same class. A redirecting constructor’s body is empty, with the constructor call appearing after a colon (:).


class Point {
num x, y;

// The main constructor for this class.
Point(this.x, this.y);

// Delegates to the main constructor.
Point.alongXAxis(num x) : this(x, 0);
}

关于flutter - 命名为 ":"的构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59519531/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com