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.
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2021-08-02 11:00:00 +0000
Seen: 8 times
Last updated: Apr 30 '22
In a new Flutter project on Android Studio, is it possible to not have any libs or main.dart file?
How can Google calendar events be generated on the server-side using Flutter?
How can I retrieve an SVG image from a URL in Flutter?
How can I combine streams of different types in Dartlang using rxdart?
What are the steps to disable FlutterFire configuration?
How can zooming similar to desktop be achieved in HTML webview browser using Flutter?
How to imitate Http Client calls during flutter testing?
What is the process of invoking a Cloud Function in Firebase through Flutter?