定义一个在Dart中获取参数的getter

时间:2014-01-03 18:12:31

标签: dart getter

我想定义一个可以选择接受参数的getter。我设法实现了这个目标,但只有在我通过电话后强制性()之后才能实现。这是代码:

get children => ([role=null]) {
  if(role == null || role == 'any') { return _children;               }
  else                              { return _children_by_role[role]; }
};

所以现在我可以说

obj.children('something').length;

obj.children().length;

但我不能说

obj.children; // this doesn't work

因为它会导致以下错误:

Caught Closure call with mismatched arguments: function 'length' NoSuchMethodError : method not found: 'length' Receiver: Closure: ([dynamic])

3 个答案:

答案 0 :(得分:5)

在Dart中,getter与访问对象属性无法区分,因此定义接受参数的getter是违法的(即使它是可选的)。

你的getter不带参数,但是使用=>运算符,返回一个带有可选参数的匿名函数。所以,obj.children是一个函数;因此,语句obj.children.length;是一个错误,因为函数没有属性length

您可能无法省略括号,但如果get children不是getter函数,您的代码会更自然地工作:

getChildren([roll]) { // null is the default value implicitly
  if (roll == null || roll == 'any') return _children;
  else return _children_by_roll[roll];
}

用作:

obj.getChildren().length;

或:

obj.getChildren(rollObject).length;

答案 1 :(得分:3)

不允许吸气者有任何争论。

你已经通过返回一个闭包而设法解决了这个问题,但这要求使用()语法(在这种情况下它不比常规函数好很多)。

如果你真的决定使用getter语法,你可以使用function emulation和委托的组合来获得你想要的几乎所有东西:

class ChildrenGetter {

  List _children;

  ChildrenGetter(this._children);

  // Function emulation: will be called whenever () is used on
  // a ChildrenGetter instance, e.g. childrenGetter();
  call([role = null]) {
    if(role == null || role == 'any') { return _children;               }
    // Omitted for scope of example, you should be able to 
    // modify to have this work
    //else                              { return _children_by_role[role]; }
  }

  // Delegate length
  get length => _children.length;

  // Delegate every other operator, method, getter, setter... 

}

现在你的吸气剂可以定义为:

get children => new ChildrenGetter(_children);

(在实际代码中,您不希望每次都返回一个新实例,但为了示例,这是最简单的。)

您现在可以调用以下任何内容并获得正确的结果:

obj.children();
obj.children.length;        
obj.children('any').length;

由于您在使用()调用时返回一个充当函数的类,但是也可以包含委托给实际子节点的getter,setter,方法和运算符。

您将遇到的一个问题是,obj.children将引用ChildrenGetter的实例,而不是代表的子女。

我不确定我会推荐这种方法,除非有充分的理由,但有趣的是要注意它可以完成。

答案 2 :(得分:1)

吸气者不接受争论。您应该只使用一个或多个默认参数定义一个函数,以实现您想要的效果。