TzeroEM
TzeroEM

Reputation: 41

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 = "[email protected]";
}
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'.

Upvotes: 4

Views: 1389

Answers (1)

Ivo
Ivo

Reputation: 23277

.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

At the time of writing this (2024-02-22 and onwards), you can check the specification herein

Upvotes: 7

Related Questions