Multiple ways to the private constructor in Dart | Flutter with examples
This tutorial shows how to create a private
constructor
in Dart and Flutter.
There is no keyword private
in Dart language.
you can check another post on declaring private variables in Dart language.
How do you make a private constructor in dart classes?
You can make a private constructor using the _
operator to empty brackets ()
.
Generally, a Private constructor allows you not to create an object or instance of a class. This will be called inside the class only. It throws an exception if the object of the class is created or extends the class.
Hence, Private constructors are useful to create a Singleton pattern.
How to declare a Private constructor?
A constructor can be added with private using a named constructor with underscore
(_) syntax
class Employee {
Employee._() {}
}
if you are creating an object of a class, It throws Error: Couldn’t find constructor ‘Employee’.
void main() {
var employee= Employee();
}
Again, If you are extending the class which has a private constructor, You can call using the super keyword as given below
class AdminEmployee extends Employee {
AdminEmployee() : super._();
}
Employee and AdminEmployee should be in the same file, If it is an indifferent file, throws a compilation
error.
here is a complete code
class Employee {
Employee._() {}
}
class AdminEmployee extends Employee {
AdminEmployee() : super._();
}
void main() {
var employee = Employee(); //Error: Couldn't find constructor 'Employee'.
}
Similarly, You can also create abstract classes which can create private constructors, But Abstract classes are not intended for using the private constructor.
Private Constructor features:
- Object of a class is not allowed
- Extend the class is not possible