{

Multiple ways to the private constructor in Dart | Flutter with examples


Private Constructor in Dart and Flutter

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

Perl How to: Find a Given Variable String is numeric or not

Dart/Flutter: Check if String is Empty, Null, or Blank example

How to generate Unique Id UUID in Dart or Flutter Programming| Dart or Flutterby Example

How to Sort List of numbers or String in ascending and descending in Dart or Flutter example

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

Dart Example - Program to check Leap year or not

Dart Example to count the number of digits in a number| Decimals Count in Dart