{

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? 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.

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.





Related posts

Dart| Flutter How to: Find a Given String is numeric or not

How to iterate loop Enum in Dart | Get Enum with index in Flutter By Example

Dart Enum comparison operator| Enum compareByIndex example| Flutter By Example

Dart tutorial examples/ Flutter By Examples

How to add Methods or Values to Enums in Dart | Flutter By Example

How to convert Double to Integer or Integer to double in Dart| Flutter By Example

How to: Enum to String in Dart | Print Enum name as String in Flutter By Example