[英]Dart: Assigning default values to optional parameters errors
I have a bunch of variables in my class, but not every one of them is required in every setting.我的 class 中有一堆变量,但并非每个设置都需要其中的每一个。 I want them to be assignable via the constructor, but only optionally.我希望它们可以通过构造函数分配,但只是可选的。
I've run into the problem of assigning default values based the constants I have defined in the very same class. This is all of the relevant code:我遇到了根据我在同一个 class 中定义的常量分配默认值的问题。这是所有相关代码:
class ExerciseSettings {
// Units available
static const List<String> repUnits = ["x"];
static const List<String> timeUnits = ["s", "min", "h"];
static const List<String> weightUnits = ["kg", "lbs"];
static const List<String> intensityUnits = ["/10"];
// Attributes needed to be assigned
bool useReps = true;
bool useWeight = true;
String repUnit = repUnits[0];
String timeUnit = timeUnits[0];
String weightUnit = weightUnits[0];
String intensityUnit = intensityUnits[0];
ExerciseSettings({
this.useReps, // This errors with the "null value" error as described below
this.useWeight,
this.repUnit = repUnits[0], // These two error with "value must be a constant"
this.timeUnit = ExerciseSettings.repUnits[0],
this.weightUnit = const repUnits[0], // And these two error with "... is not a class"
this.intensityUnit = const ExerciseSettings.repUnits[0]
});
This errors with "The parameter 'useReps' can't have a value of 'null' because of its type, but the implicit default value is 'null'. Try adding either an explicit non-'null' default value or the 'required'".此错误与“参数'useReps'由于其类型不能具有'null'值,但隐式默认值为'null'。尝试添加显式非'null'默认值或'required' '”。
I don't understand why this is.我不明白这是为什么。 First of, why is initializing the variables not taken into account?首先,为什么不考虑初始化变量? They have values assigned, meaning they shouldn't be null.它们已分配值,这意味着它们不应该是 null。
Second of, why can I not assign the static constants as default values inside the constructor?其次,为什么我不能在构造函数中将 static 常量指定为默认值?
Yo can't pass a list item to a constant value, so try this:你不能将列表项传递给常量值,所以试试这个:
class ExerciseSettings {
// Units available
static const List<String> repUnits = ["x"];
static const List<String> timeUnits = ["s", "min", "h"];
static const List<String> weightUnits = ["kg", "lbs"];
static const List<String> intensityUnits = ["/10"];
// Attributes needed to be assigned
final bool? useReps;
final bool? useWeight;
final String? repUnit;
final String? timeUnit;
final String? weightUnit;
final String? intensityUnit;
ExerciseSettings({
this.useReps = true,
this.useWeight = true,
String? repUnit,
String? timeUnit,
String? weightUnit,
String? intensityUnit,
}) : repUnit = repUnit ?? repUnits[0],
timeUnit = timeUnit ?? ExerciseSettings.repUnits[0],
weightUnit = weightUnit ?? repUnits[0],
intensityUnit = intensityUnit ?? ExerciseSettings.repUnits[0];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.