flutter - 这个以Classname为前缀的class-const-Syntax在Dart中是什么意思?

标签 flutter dart

尽管我自认为熟悉编程语言 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 中,您可以通过两种方式定义构造函数,使用 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

关于flutter - 这个以Classname为前缀的class-const-Syntax在Dart中是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65372981/

相关文章:

visual-studio - 在 Visual Code Studio 中哪里可以找到 Flutter 布局检查器?

dart - 在 flutter 中将小部件封装在它自己的类中?

dart - 如何从 Flutter 元素中读取数据

flutter/Dart : How to decompress/inflate zlib binary string in flutter

dart - 创建安全服务器证书的文件相对路径

flutter - 在ListView.builder() flutter中动态创建单选按钮Group

Flutter 抽屉背景图片

dart - 我尝试使用 TextField 的 Controller ,但我收到错误 "NoSuchMethodError: The method ' 调用' was called on null"

mongodb - 维护的Dart ORM(特别适用于mongodb)

json - 如何将嵌套的 JSON 转换为对象