简体   繁体   English

Class.new 在 Dart 中做了什么

[英]What does Class.new do in Dart

I'm currently dealing with Flutter among others with Riverpod.我目前正在与 Riverpod 处理 Flutter 等。 In one of the examples I came across the following code-line.在其中一个示例中,我遇到了以下代码行。
final repositoryProvider = Provider(MarvelRepository.new);最终 repositoryProvider = Provider(MarvelRepository.new);

final repositoryProvider = Provider(MarvelRepository.new);

class MarvelRepository {
  MarvelRepository(
    this.ref, {
    int Function()? getCurrentTimestamp,
  }) : _getCurrentTimestamp = getCurrentTimestamp ??
            (() => DateTime.now().millisecondsSinceEpoch);
  
  final Ref ref;
  final int Function() _getCurrentTimestamp;
  final _characterCache = <String, Character>{};
  ...
  ...
  ...
}

I was wondering how this "new" property works here.我想知道这个“新”属性是如何在这里工作的。 I tried to find something in the documentation and in the specification.我试图在文档和规范中找到一些东西。
I built a simple class to examine the code.我构建了一个简单的 class 来检查代码。

class User {
      User();
      final String name = "MisterX";
      final String email = "misterx@gmail.com";
}
void main() {
  
    final x = User.new;
    final z = x();   
    print(z.email);
   
}

'x' now seems to me to be a new class with which I can create further instances. 'x' 现在在我看来是一个新的 class ,我可以用它创建更多实例。
But what is actually happening here?但这里实际发生了什么?

Why can I use it to create another provider instance?为什么我可以使用它来创建另一个提供程序实例?

What is the difference to:有什么区别:
final repositoryProvider = Provider((ref) => MarvelRepository(ref)); final repositoryProvider = Provider((ref) => MarvelRepository(ref));

final repositoryProvider = Provider<MarvelRepository>((ref) => MarvelRepository(ref));

class MarvelRepository {
  MarvelRepository(
    this.ref, {
    int Function()? getCurrentTimestamp,
  }) : _getCurrentTimestamp = getCurrentTimestamp ??
            (() => DateTime.now().millisecondsSinceEpoch);
  
  final Ref ref;
  final int Function() _getCurrentTimestamp;
  final _characterCache = <String, Character>{};
  ...
  ...
  ...
}

Here is the example found in 'marvel.dart'.这是在“marvel.dart”中找到的示例

.new is a way to pass a reference to the constructor. .new是一种将引用传递给构造函数的方法。 It doesn't create a new class.它不会创建新的 class。 It's just the same default constructor of the class.它与 class 的默认构造函数相同。 This is also called a constructor tear-off.这也称为构造函数撕裂。 It was introduced in Dart 2.15.它是在 Dart 2.15 中引入的。 You can read more about it here:你可以在这里读更多关于它的内容:

Announcing Dart 2.15宣布 Dart 2.15

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM