8 class default-value dart flutter
我创建了一个类JobBloc,其中包含许多属性,其中一个属性是另一个类对象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,
});
}
Run Code Online (Sandbox Code Playgroud)
如何为我的jobModel属性分配默认值?
Jac*_*Lee 10
您无法初始化类模型中的对象。
尝试:
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);
}
Run Code Online (Sandbox Code Playgroud)
或者更新 jobModel 类
class JobModel {
final String name;
final double ratePerHour;
JobModel({
this.name = 'EMPTY',
this.ratePerHour = 0.01,
});
}
Run Code Online (Sandbox Code Playgroud)