Search⌘ K
AI Features

Class Constructors

Explore how to define and use class constructors in Dart, including normal, optional, and named optional constructors. Understand how these constructors manage fields and default values to write cleaner and more effective Flutter applications.

Since Dart is an object-oriented programming language, we should be familiar with its constructors. In this lesson, we’ll learn about constructors and look at various ways to build the constructors of a class.

Normal constructor

Dart
class Student {
String name;
int age;
// constructor
Student(String name, int age) {
this.name = name;
this.age = age;
}
}

For those with a Java background, this will look familiar. Now let’s look at it in a more sugar-syntactic way:

Dart
class Student {
String name;
int age;
Student(this.name, this.age);
}

Defining a constructor in this way is fine, and the Dart will mean it ...