首页 > 解决方案 > 这个以 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,
  });

标签: flutterdart

解决方案


那是一个命名的构造函数。在 dart 中,您可以通过两种方式定义构造函数,使用ClassNameClassName.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


推荐阅读