I created a class JobBloc that contains a number of properties one of which is another class object JobModel, I want to assign a default value to each of these properties, it works fine except for the JobModel property:

class JobBloc with JobModelFormValidator {
  final JobModel jobModel;
  final bool isValid;
  final bool showErrorMessage;
  final String name;
  final double ratePerHour;
  final bool enableForm;
  final bool showIcon;

  JobBloc({
    // The default value of an optional parameter must be constant.
    this.jobModel = JobModel(name: 'EMPTY', ratePerHour: 0.01), // <= the error stems from this line
    this.isValid = false,
    this.showErrorMessage = false,
    this.name = 'EMPTY',
    this.enableForm = true,
    this.ratePerHour = 0.01,
    this.showIcon = false,
    });
}

How can I assign a default value to my jobModel property?


Solution 1: Mathis Fouques

Try this may be ?

class JobBloc with JobModelFormValidator {
  final JobModel jobModel;
  final bool isValid;
  final bool showErrorMessage;
  final String name;
  final double ratePerHour;
  final bool enableForm;
  final bool showIcon;

  JobBloc({
    this.jobModel = const JobModel(name: 'EMPTY', ratePerHour: 0.01),
    this.isValid = false,
    this.showErrorMessage = false,
    this.name = 'EMPTY',
    this.enableForm = true,
    this.ratePerHour = 0.01,
    this.showIcon = false,
    });
}


Solution 2: Jackson Lee

You can't initialize an object in a class model.

Try:

class JobBloc with JobModelFormValidator {
  final JobModel jobModel;
  final bool isValid;
  final bool showErrorMessage;
  final String name;
  final double ratePerHour;
  final bool enableForm;
  final bool showIcon;

  JobBloc({
    this.isValid = false,
    this.showErrorMessage = false,
    this.name = 'EMPTY',
    this.enableForm = true,
    this.ratePerHour = 0.01,
    this.showIcon = false,
    }) : jobModel = JobModel(name: 'EMPTY', ratePerHour: 0.01);
}

Or update the jobModel class

class JobModel {
  final String name;
  final double ratePerHour;

  JobModel({
    this.name = 'EMPTY',
    this.ratePerHour = 0.01,
  });
}