Dart Flutter:为class构造函数设置默认值时,可选参数的默认值必须为常量

Dart Flutter: The default value of an optional parameter must be constant when setting a default value to class constructor

我创建了一个 class JobBloc,其中包含许多属性,其中一个是另一个 class 对象 JobModel,我想为每个属性分配一个默认值在这些属性中,它工作正常,除了 JobModel 属性:

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,
    });
}

如何为 jobModel 属性 分配默认值?

试试这个可能是?

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,
    });
}

您不能在 class 模型中初始化对象。

尝试:

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);
}

或者更新 jobModel class

class JobModel {
  final String name;
  final double ratePerHour;

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