1 | initial version |
In Dart, multiple constructors can be implemented using the factory
keyword.
For example, suppose we have a class named Person
with the following properties:
class Person {
String name;
int age;
Person(this.name, this.age);
}
We can add another constructor that accepts only the name of the person and sets the age to a default value of 18. To do this, we use the factory
keyword and create a named constructor:
class Person {
String name;
int age;
Person(this.name, this.age);
factory Person.fromName(String name) {
return Person(name, 18);
}
}
Now, we can create a new Person
object with just the name parameter by calling the named constructor like this:
var john = Person.fromName('John');
This will create a new Person
object with the name "John" and age 18.
Note that the fromName
constructor is a factory
constructor because it does not create a new instance of the class directly, but instead returns an existing instance created within the constructor using the return
keyword.