How to use **kwarg in Dart (like in Python)

Viewed 193

I have a question on how to easily use map as a parameter in Dart. Is there any easy way of passing all the key-values pairs of a map object to a function?

For example, I have a map and a function like this:

const testMap = {"a": 1, "b":2};

int testFunc(a, b){
  return a + b;
}

and I want to use them like this:

testFunct(**testMap) // not possible in dart (though possible in python)

which should give us 3 as the result.

Any smart solution like this? Thanks!


Please note that ** is the python-way of passing the parameters inside dictionary: docs

1 Answers

It's not directly possible the way you write it, but you can do something similar using Function.apply.

You have to either pass the arguments as positional, and then you need to know the order:

const testMap = {"a": 1, "b":2};

int testFunc(a, b){
  return a + b;
}

void main() {
  print(Function.apply(testFunc, testMap.values.toList()));
}

or you have to use named parameters and then the map keys should be symbols:

const testMap = {#a: 1, #b:2};

int testFunc({required int a, required int b}){
  return a + b;
}

void main() {
  print(Function.apply(testFunc, [], testMap));
}

Dart distinguishes positional and named parameters, so if you want to refer to a parameter by name, it should be named.

The former approach is dangerous because you don't use the names of the map. It should really just be const testArguments = [1, 2]; and not include a map which doesn't help you.

Using Function.apply is not type safe. It's as type-safe as calling something with type dynamic or Function — which means not safe at all — so use it carefully and only when necessary.

Related