0

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,
}) {
  ....
}

I tried adding const but that didn't work as it expects map part to be a class.

int msDuration = const toastDuration["default"],

aWebDeveloper
  • 36,687
  • 39
  • 170
  • 242

2 Answers2

2

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,
}) {
    ...
}
Yair Chen
  • 917
  • 6
  • 10
0

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.

Magnuti
  • 63
  • 9