'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;
}


Solution 1:[1]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Kirill Bubochkin