Reputation: 41
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
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:
At the time of writing this (2024-02-22 and onwards), you can check the specification herein
Upvotes: 7