Reputation: 35
I have found some codes that got me confused regarding "this" keyword and the colon after the constructor.
I want to know what the difference between the two is, and what they are for.
Using colon
class BusinessLogic {
const BusinessLogic({
required DataRepository repository,
}) : _repository = repository;
final DataRepository _repository;
}
Using this
keyword
class BusinessLogic {
const BusinessLogic({
required this.repository,
});
final DataRepository repository;
}
Upvotes: 1
Views: 95
Reputation: 6353
In the first sample, _repository
is a private member, in the second sample, repository
is a public member.
Apart from that, there's no difference, so if you go with public members everywhere, these 2 samples will be equivalent:
class BusinessLogic {
const BusinessLogic({
required DataRepository repository,
}) : repository = repository;
final DataRepository repository;
}
// same as:
class BusinessLogic {
const BusinessLogic({
required this.repository,
});
final DataRepository repository;
}
In Dart, this construction (in the second sample) is called "initializing parameters". You can read more on that here.
Upvotes: 3