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? Generally, a Private constructor allows you not to create an object or instance of a class.
Private constructors are useful to create a Singleton pattern.
Dart Private constructor
A constructor can be added with private using 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.