Home > database >  How do I make the map value a constant in function parameter in dart [duplicate]
How do I make the map value a constant in function parameter in dart [duplicate]

Time:10-01

Why does dart complain "The default value of an optional parameter must be constant". How do I make the map value constant

Map<String, int> toastDuration = {
  "defaut": 4000,
};

void showToast({
  BuildContext context,
  String msg,
  int msDuration = toastDuration["default"], // Error: The default value of an optional parameter must be constant
  bool hidePrev = true,
}) {
  ....
}

CodePudding user response:

toastDuration["default"] can't be constant because it's an expression calculated later (Think about the fact you can put any string in the braces). You can do something similar like that:

const defaultToastDuration = 4000;
Map<String, int> toastDuration = {
  "default": defaultToastDuration,
}

void showToast({
  BuildContext context,
  String msg,
  int msDuration = defaultToastDuration,
  bool hidePrev = true,
}) {
    ...
}

CodePudding user response:

As the error message says The default value of an optional parameter must be constant. Think about what happens if you remove the default key from toastDuration. Instead of using a map here you can simply use the default value directly.

void showToast({
  BuildContext context,
  String msg,
  int msDuration = 4000,
  bool hidePrev = true,
})

Another problem in your original code is that if you change the default key to say 300, the showToast will break because default parameters must be constants.

  • Related