flutter - 这个以 Classname 为前缀的 class-const-Syntax 在 Dart 中是什么意思?
问题描述
尽管我认为熟悉编程语言 Dart,但我在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
推荐阅读
- sql - 分布式查询的谓词中是否为空条件不远程运行
- android - RecyclerView子项点击onBindViewHolder()
- angular - 使用 3 个组件 Angular 将值从弹出窗口传递到父页面
- twilio - Twilio 运行时客户端 SDK
- javascript - 我需要使用 jquery 从 url 中删除一个字段
- javascript - 在数组中查找最佳路线和价格
- vertica - 如何使用 vertica 格式化日期时间
- css - 隐藏在地图下的对象 [反应]
- reactjs - 无法读取未定义的属性“地图” - 不从道具读取数组
- javascript - 如何在 javascript 文件中的所有 html 标记之间包含 javascript