I would like to define a getter that can optionally take arguments. I managed to achieve that, however it only works if I put the obligatory ()
after the call. Here's the code:
get children => ([role=null]) {
if(role == null || role == 'any') { return _children; }
else { return _children_by_role[role]; }
};
So now I can say
obj.children('something').length;
or
obj.children().length;
but I cannot say
obj.children; // this doesn't work
because it results in the following error:
Caught Closure call with mismatched arguments: function 'length' NoSuchMethodError : method not found: 'length' Receiver: Closure: ([dynamic])
In Dart, getters are meant to be indistinguishable from accessing object properties, so it is illegal to define a getter that accepts an argument (even if it's optional).
Your getter takes no arguments, but with the =>
operator, returns an anonymous function that takes an optional argument. So, obj.children
is a function; therefore the statement obj.children.length;
is an error because functions don't have the property length
.
You may not be able to omit the parentheses, but your code would work more naturally if get children
wasn't a getter function:
getChildren([roll]) { // null is the default value implicitly
if (roll == null || roll == 'any') return _children;
else return _children_by_roll[roll];
}
used as:
obj.getChildren().length;
or:
obj.getChildren(rollObject).length;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With