Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

in defining a function in Dart, how to set an argument's default to { }, ie, an empty Map?

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.

like image 863
cc young Avatar asked Nov 25 '13 08:11

cc young


People also ask

What is default Dart value?

Default valueUninitialized variables that have a nullable type have an initial value of null . (If you haven't opted into null safety, then every variable has a nullable type.) Even variables with numeric types are initially null, because numbers—like everything else in Dart—are objects.

How do you specify optional parameters in DART?

Named optional parameters You can call getHttpUrl with or without the third parameter. You must use the parameter name when calling the function. You can specify multiple named parameters for a function: getHttpUrl(String server, String path, {int port = 80, int numRetries = 3}) { // ... }

What is parameter in Dart?

Dart Masterclass Programming: iOS/Android Bible Parameters are a mechanism to pass values to functions. Parameters form a part of the function's signature. The parameter values are passed to the function during its invocation.

Does DART pass by value?

Dart currently only allows passing arguments by value (where object references are values).


2 Answers

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

like image 141
Alexandre Ardhuin Avatar answered Oct 12 '22 22:10

Alexandre Ardhuin


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 = {};
  ...
}
like image 25
lrn Avatar answered Oct 13 '22 00:10

lrn