Dart中,Classname前缀的class-const-Syntax是什么意思?

3
尽管我认为自己对编程语言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 AuthenticationState._({
    this.status = AuthenticationStatus.unknown,
    this.user = User.empty,
  });
2个回答

2

这是一个命名构造函数。在dart中,你可以用两种方式来定义构造函数,一种是使用ClassName,另一种是使用ClassName.someOtherName

例如:假设你有一个名为person的类,有两个变量,name和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 语言指南

0

由于上面的回答对我来说不是很清晰/完整,当我偶然发现这个问题时,请让我知道我的理解是否正确:

const AuthenticationState._({
    this.status = AuthenticationStatus.unknown,
    this.user = User.empty,
  });

构造函数使用._()是库私有的,我猜这是一种安全特性,所以你只能从库内部创建实例。
const AuthenticationState.unknown() : this._();

如果对象被创建为.unknown,则会调用上面的默认构造函数(作为私有函数),因此使用默认值。在另外两种情况下,一个或两个默认值将被替换。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接