Reputation: 20203
love how Dart
treats function arguments, but cannot accomplish what should be a simple task:
void func( String arg1, [ Map args = {} ] ) { ... }
get the error
expression is not a valid compile-time constant
have tried new Map()
for example, with same error.
Upvotes: 6
Views: 3613
Reputation: 71623
The default value must be a compile time constant, so 'const {}' will keep the compiler happy, but possibly not your function.
If you want a new modifiable map for each call, you can't use a default value on the function parameter. That same value is used for every call to the function, so you can't get a new value for each call that way. To create a new object each time the function is called, you have to do it in the function itself. The typical way is:
void func(String arg1, [Map args]) {
if (args == null) args = {};
...
}
Upvotes: 5
Reputation: 76183
You have to use the const
keyword :
void func( String arg1, [ Map args = const {} ] ) {
...
}
Warning : if you try to modify the default args
you will get :
Unsupported operation: Cannot set value in unmodifiable Map
Upvotes: 10