尽管我自认为熟悉编程语言 Dart,但我在 example 中偶然发现了这种语法。对于 Bloc :
class AuthenticationState extends Equatable {
const AuthenticationState._({
this.status = AuthenticationStatus.unknown,
this.user = User.empty,
});
const AuthenticationState.unknown() : this._();
const AuthenticationState.authenticated(User user)
: this._(status: AuthenticationStatus.authenticated, user: user);
const AuthenticationState.unauthenticated()
: this._(status: AuthenticationStatus.unauthenticated);
final AuthenticationStatus status;
final User user;
@override
List<Object> get props => [status, user];
}
我知道如何定义类常量和 const 构造函数。
可是,为什么这里到处都是类名前缀呢?
const AuthenticationState._({
this.status = AuthenticationStatus.unknown,
this.user = User.empty,
});
最佳答案
这是一个命名的构造函数。在 dart 中,您可以通过两种方式定义构造函数,使用 ClassName 或 ClassName.someOtherName。
例如:假设您有一个名为 person 的类,它有 2 个变量,name 和 carNumber。每个人都有名字,但 carNumber 不是必需的。在那种情况下,如果您实现默认构造函数,则必须像这样初始化它:
Person("Name", "");
所以如果你想添加一些语法糖,你可以添加一个命名构造函数,如下所示:
class Person {
String name;
String carNumber;
// Constructor creates a person with name & car number
Person(this.name, this.carNumber);
// Named constructor that only takes name and sets carNumber to ""
Person.withOutCar(String name): this(name, "");
// Named constructor with no arguments, just assigns "" to variables
Person.unknown(): this("", "");
}
您可以像这样初始化对象:
Person.withOutCar("Name");
在上面的示例中,命名构造函数被重定向到具有预定义默认值的实际构造函数。
您可以在此处阅读有关命名构造函数的更多信息:Dart Language Tour
关于flutter - 这个以Classname为前缀的class-const-Syntax在Dart中是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65372981/