简体   繁体   中英

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. 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 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'".

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.

Second of, why can I not assign the static constants as default values inside the constructor?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM