Constructors

Classes can have constructors. A constructor is a special method that is automatically called when an object of a class is created. It can be used to set initial values for properties of the class. For instance, let's change our code to use a constructor to build a Person instance:

main() { 
Person clark = Person('Clark', 'Kent');
print ('${clark.name} ${clark.surname}');

}
class Person {
String name, surname;
Person(String name, String surname) {
this.name = name;
this.surname = surname;
}
}

Person(name, surname) is a constructor method that requires two parameters: name and surnameYou are required to pass both parameters when you create a new instance of the class. For example, if you try to create a  Person instance, without passing two strings, you receive an error. You can make positional parameters optional by enclosing them in square brackets:

Person([String name, String surname]) {

Now, what if you want to add a second constructor that takes no parameters? You could try to add the second constructor as follows:

 Person();

However, you would get an error: "The default constructor is already defined." That's because, in Dart, you can have only one unnamed constructor, but you can have any number of named constructors. In our example, we could add the following code:

 Person.empty() {

This would create a second named constructor. In the following screenshot, you can see an example of a class with an unnamed constructor, Person(), and a named constructor, person.empty()

In this case, the difference between the two is that when you call the default (unnamed) constructor, you also need to pass the two required parameters, name and surname, while the named constructor allows you to create an empty object and then set the name and surname later in your code.

Just to reiterate, you can have only one default unnamed constructor in Dart, but you can have as many named constructors as you need.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.187.62