I am trying to learn Dart language along with flutter. I have come across the following piece of code (taken from here: https://github.com/ppicas/flutter-android-background/blob/master/lib/counter_service.dart) :
import 'package:flutter/foundation.dart';
import 'counter.dart';
class CounterService {
factory CounterService.instance() => _instance;
CounterService._internal(); <<====================== Why is this line here ? What does it do?
static final _instance = CounterService._internal();
final _counter = Counter();
ValueListenable<int> get count => _counter.count;
void startCounting() {
Stream.periodic(Duration(seconds: 1)).listen((_) {
_counter.increment();
print('Counter incremented: ${_counter.count.value}');
});
}
}
I could not figure out why the line of code is required there. I understand that we force returning a single instance of this class by implemented a private constructor and the only instance is created in the following line. So, why do we really have to have that line there?
I’d appreciate if a dart expert shed some light over it. Thanks
2
Answers
Is a private named constructor that creates an object and can be called only within the class (privacy).
Is a public named constructor that returns an object (
CounterService object
) and can be called outside the class.Now the question:
How can the client of that class create an object?
answer: he just calls
CounterService.instance()
which always return an object we have already instantiated from the internal private constructor. remember!_instance is a private object of the same type of its class, it’s a composition
Note: it’s created using the private constructor, while the public constuctor always returns it.
So, what’s the purpose of the above code?
it aims to return only one object of that class, it’s a conformation to Singleton Design Pattern.
Hope it helps you.
_internal
is a named constructorIt is also private as it starts with an underscore, so can only be called from within the same source file (typically).
If you didn’t have any constructor, Dart would provide a default constructor, which would be public and callable anywhere, allowing anyone to construct another instance of what you hope is a singleton.
In Dart, the pattern to create a singleton is to use two named constructor (no need for the default constructor) one private and one public. The public one is a factory that simple returns the single static instance that was created using the private constructor.