Dart named and factory constructor

Created At: 2023-08-19 20:12:26 Updated At: 2023-08-19 21:16:17

Dart constructors are methods with class name itself but without a return statement. In general we use constructors to create object or an instance of a class.

We need create a class that has properties and some methods. A method that has no return statement in general that becomes a constructor but you need to make sure that the method name as the class name.

Dart default constructor 

Dart default constructor are something that you don't see by default. It always exsit there. See the example below.

We created a class, and the class has three properties or fields. Then on line 12 we created a instance or object called profile using UserProfile().

Even though we don't have any constructor inside the class name but Dart compiler will automitically assign one.

But how do we prove that it's a default constructor? Well we can put a put body of the constructor by using curly brace on line 8 and the put a print statement in it.

Here in you run the code, you will see default constructor printed on the terminal. The constructor is called and it's body executed. 

Even if you remove UserProfile() from line 5, Dart will still assign one but in this case you won't see it. 

Dart parameterized constructor

Dart parameterized constructor takes parameters in its constructor as you can see below. 

Here we see on line 8, we have a constructor as UserProfile(). This is a constructor and you see it does not have return statement. This is also called parameterized constructor. These are also positional parameters since you need to put them in order when you call the constructor to create instance.

Factory constructor 

First thing factory constructor looks like a method and it has factory modifier in front of the the name. Since you can use custom name that means you can create many constructors as your needs which is flexible in terms of creating dart objects.

But you need to make sure you have a generic constructor before you can create a factory constructor.

You may write your factory constructor like this 

factory YourClassName.customName(){

 return YourClassName();

}

So from your controller or UI you will call YourClassName.customName(). As you see internally we still return a generic constructor.

Then you may ask what’s the benefit of using a Factory constructor. There are a few benefits to see

  1. Return a sub class
  2. Return a cached instance 
  3. Return instance based on condition 
  4. Passing argument to factory constructor 
  5. It may also throw exception 

Comment

Add Reviews