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

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)

  • 构造函数后面的冒号在 Flutter 中称为初始化列表。它允许您初始化类的字段、进行断言并调用超级构造函数。如果您想了解更多信息:https://dart.dev/guides/language/language-tour#initializer-list (3认同)