{

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: Read pubspec.yaml attributes (version) with examples

How to Create and build a Singleton Class Dart or Flutter example| Dart By Example

What is the difference between var and dynamic and final in dart?| Flutter By Example

How to: Check if Phone number is valid or not in Dart| Flutter By Example

Dart| Flutter How to read an image from a disk and resize a file

Dart/Flutter: How to write setter and getter fields or members variables in a class with Example

Dart| Flutter How to get extension name and MIME type of a file with example