What is the new keyword in Dart?

Overview

The new keyword is used to create an instance of a class. However, Dart 2 makes the new keyword optional. Calling a class will always return a new instance of that class.

Syntax

class class_name = new class_name( [arguments]);

Example

class Person {
  // some code
 }

void main() {
    Person person = new Person();
}

In Dart 2, using the new keyword is optional. The code above can be written as the following:

class Person {
  // some code
 }

void main() {
    Person person =  Person();
}

Let's look at the code below to further understand:

class Person {
// class properties
String firstName = 'Maria';
String lastName = 'Elijah';
// class method
void display() {
print('My name is $firstName $lastName');
}
}
void main() {
// Creating an object of class Person
Person person = new Person();
// invoke class method using its instance
person.display();
}

Explanation

  • Lines 1–10: We create a class, Person, which has the properties, firstName and lastName. Next we create a method, display().

  • Lines 12: We create a main() function.

  • Line 14: We create an object of class Person named person.

  • Line 16: We invoke the class method, display(), using person.

Free Resources