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.
class class_name = new class_name( [arguments]);
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 propertiesString firstName = 'Maria';String lastName = 'Elijah';// class methodvoid display() {print('My name is $firstName $lastName');}}void main() {// Creating an object of class PersonPerson person = new Person();// invoke class method using its instanceperson.display();}
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
.