Kenneth Terrago
Kenneth Terrago

Reputation: 35

Dart: What is the difference when using this keyword and colon after the constructor?

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

Answers (1)

Kirill Bubochkin
Kirill Bubochkin

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

Related Questions