Ask Your Question
1

How can multiple constructors be implemented in Dart?

asked 2021-08-02 11:00:00 +0000

devzero gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2022-04-30 14:00:00 +0000

qstack gravatar image

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.

edit flag offensive delete link more

Your Answer

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

Add Answer


Question Tools

Stats

Asked: 2021-08-02 11:00:00 +0000

Seen: 8 times

Last updated: Apr 30 '22