Jyhonn
Jyhonn

Reputation: 83

How to reuse constructor on multiple named constructors in Dart?

I have this model class where I need to build different instances based on different conditions from data input. Below is an example of my current solution.

I am wondering if there's anyway I can reuse the base constructor?

Because in real case, the base constructor is way more complicated, and there are a lot of conditions. I have to copy and paste the base constructor's parameters many times.

Or there's other cleaner patterns I can use?

Code example:

class PersonModel {
  int id;
  String name;  
  int age; 
  String? job; 
  String? status 

  // how do I reuse this base constructor code on multiple named constructors?
  PersonModel.base({     
    required this.id,
    required this.name,
    required this.age,
  })
  
  PersonModel.condition1({
    required this.id,
    required this.name,
    required this.age,
    required this.job,
  })

  PersonModel.condition2({
    required this.id,
    required this.name,
    required this.age,
    required this.job,
    required this.status,
  })
  
  factory PersonModel.fromMap(Map<String, dynamic> data) {
    int id = data["id"];
    if (id <= 100) {
       return PersonModel.base({}); // omit parameters for demonstration
    } else if (id <=150) {
       return PersonModel.condition1({}); // omit parameters for demonstration
    } else {
       return PersonModel.condition2({}); // omit parameters for demonstration
    }
  }
}

Upvotes: 0

Views: 840

Answers (1)

jamesdlin
jamesdlin

Reputation: 89926

You can make one constructor leverage another one by using redirecting constructors. In your case, you'd do:

  PersonModel.base({     
    required this.id,
    required this.name,
    required this.age,
  });
  
  PersonModel.condition1({
    required int id,
    required String name,
    required int age,
    required this.job,
  }) : this.base(id: id, name: name, age: age);

  PersonModel.condition2({
    required int id,
    required String name,
    required int age,
    required String? job,
    required this.status,
  }) : this.condition1(id: id, name: name, age: age, job: job);

Upvotes: 4

Related Questions