Reputation: 711
In a function with optional parameters, I want to print all the parameters passed in, not just value but also identifier of each parameter. For example, below is a function with optional named parameters. I print out both arg name and its value using a map instance, that's what I need.
Map temp = new Map();
argumentTest({String a, String b, String c: "DDD"}){
if (a != null) {
temp.addAll({"a":a});
}
if (b != null) {
temp.addAll({"b":b});
}
if (c != null) {
temp.addAll({"c":c});
}
}
void main() {
argumentTest(a:"AAA");
print('$temp'); //{a: AAA, c: DDD}
}
Though ugly, it works. But, is there anything which looks like;
Map temp = new Map();
argumentTest({String a, String b, String c: "DDD"}){
arguments.forEach((arg) => temp.addAll({"arg": arg}));
}
void main() {
argumentTest(a:"AAA");
print('$temp'); //of course, not working.
}
Thank you all and always.
Upvotes: 2
Views: 1226
Reputation: 657416
You could simplify your workaround
Map temp = new Map();
argumentTest({String a, String b, String c: "DDD"}) {
({'a': a, 'b': b, 'c': c}).forEach((k, v) {
if(v != null) temp[k] = v;
});
}
to support default values different from null
you need to extend a little - for example like
argumentTest({String a, String b, String c: "DDD"}) {
({
'a': [a, null], 'b': [b, null], 'c': [c, "DDD"]
}).forEach((k, v) {
if(v[0] != v[1]) temp[k] = v[0];
});
}
Upvotes: 4
Reputation: 966
There is no such thing in Dart. However, if you want to build mock objects for automated tests, you can take a look at this article, which shows how to use the mock package
Upvotes: 2
Reputation: 42343
I don't believe this is possible (even using mirrors). The names of your variables will be changed during minification. The "messy" coder you have is really the only way of preserving them in a way you can access like this.
Upvotes: 1