Home > other >  How to create partial models of required fields in dart
How to create partial models of required fields in dart

Time:07-31

I'm generating fake models for testing and I would like to be able to change some arguments of my fake model with a partial model

I would like also to not change my model and keep required fields since it's only for testing purpose

class OrganisationModel {
  String id;
  String name;
  String numberOfEmployee;
  String activitySector;

  OrganisationModel({
    required this.id,
    required this.name,
    required this.numberOfEmployee,
    required this.activitySector,
  });
}

OrganisationModel fakeOrganisation({OrganisationModel? partial}) {
  return OrganisationModel(
    id: partial?.id ?? '1234',
    name: partial?.name ?? 'MyCompany',
    numberOfEmployee: partial?.numberOfEmployee ?? '68',
    activitySector: partial?.activitySector ?? 'Dev',
  );
}

fakeOrganisation(partial: OrganisationModel(name: 'MyCompany2'))

Since my fields are required I need to pass all arguments as empty string and they overwrite my arguments

Current result

fakeOrganisation(partial: OrganisationModel(id: '', name: 'MyCompany2', numberOfEmployee: '', activitySector: ''))
// {id: '', name: 'MyCompany2', numberOfEmployee: '', activitySector: ''}

What I would like

fakeOrganisation(partial: OrganisationModel(name: 'MyCompany2', numberOfEmployee: '24'))
// {id: '1234', name: 'MyCompany2', numberOfEmployee: '24', activitySector: 'Dev'}

CodePudding user response:

How about:

Since OrganisationModel fields are required, they must be specified.

However, in fakeOrganisation, you re-define the parameters with default values, to be passed to the OrganisationModel.

class OrganisationModel {
  String id;
  String name;
  int numberOfEmployee;
  String activitySector;

  OrganisationModel({
    required this.id,
    required this.name,
    required this.numberOfEmployee,
    required this.activitySector,
  });
}

OrganisationModel fakeOrganisation({
  id = '1234',
  name = 'MyCompany',
  numberOfEmployee = 68,
  activitySector = 'Dev',
}) {
  return OrganisationModel(
    id: id,
    name: name,
    numberOfEmployee: numberOfEmployee,
    activitySector: activitySector,
  );
}

void main() {
  var x = fakeOrganisation(name: 'MyCompany2');
  print(x.name);
  print(x.numberOfEmployee);
}

CodePudding user response:

You can do something like

  • Related