Class Constructor in Dart.

Yogendra Singh
2 min readApr 17, 2020

--

Dart Constructor.

The constructor basically is a special type of function in object oriented language which is used to create the class instance. Following characteristics of a constructor.

  • Constructors have the same as Class name.
  • There is no return type.
  • Constructor is called automatically when the object is created.

Here is the examples how can be declare constructor in Dart.

  1. Default Constructor:
class Person {
String name;
int age;
}

Now create the instance of Person class. By adding open and close parenthesis. It initialise the properties to null.

var person = Person();
person.name = 'Yogendra';
person.age = 29;

2. Constructor without named argument.

class Person {
String name;
int age;
Person(String name, int age) {
this.name = name;
this.age = age;
}
// Or the shorthand way, make sure the name and age must match.
Person(this.name, this.age);
}

Now create the instance of Person class in this case. By writing.

var person = Person('Yogendra', 29);
print('Name: ${person.name} and Age: ${person.age}');

3. Constructor with named argument. Here just need to wrap arguments inside the open and close curly braces {} like below. In this way you can make argument optional. You may initialise with one argument or more or no.

class Person {
String name;
int age;
Person({String name, int age}) {
this.name = name;
this.age = age;
}
// Or the shorthand way, make sure the name and age must match.
Person({this.name, this.age});
}

Now create the instance of Person class in this case. By writing.

var person1 = Person(name: 'Yogendra Singh', age: 29);

In this case the sequence does not matter. Instance also can be create by writing age first then name like below. This is helpful when there are so many arguments a constructor have and all are optional.

var person = Person(age: 29, name: 'Yogendra')

If there are some arguments those are needed during the object initialisation the we can add annotation @required before the argument type and also can provide the default value of argument. like Person({@required String name, int age = 29});

4. Another type of Constructors are called Named constructors. Use a named constructor to implement multiple constructors for a class or to provide extra clarity:

class Point {
double x;
double y;
Point(self.x, self.y); Point.zero() {
x = 0.0
y = 0.0
}
}

Now create the instance of Person class in this case. By writing.

var point = Point(10, 20) // Here x = 10 and y = 20
var zero = Point.zero() // Here x and y both are 0.

Thank you!

Yogendra Singh.

--

--