简体   繁体   中英

What does Class.new do in Dart

I'm currently dealing with Flutter among others with Riverpod. In one of the examples I came across the following code-line.
final 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 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.
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<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'.

.new is a way to pass a reference to the constructor. It doesn't create a new class. It's just the same default constructor of the class. This is also called a constructor tear-off. It was introduced in Dart 2.15. You can read more about it here:

Announcing Dart 2.15

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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