You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Dart中是否可调用类内set关键字声明的setter?

Dart 中set关键字声明的setter调用说明

Dart完全支持调用类内部通过set关键字声明的setter,触发编译错误的核心原因是setter的调用语法不符合规则。

错误根因

示例代码中在构造函数里写的size(initialSize)属于普通方法的调用写法,但set声明的setter是基于属性访问语法实现的封装,本身不是可独立调用的函数,因此编译器会抛出如下错误:

Error: 'size' isn't a function or method and can't be invoked.
Error: 'color' isn't a function or method and can't be invoked.
Error: 'age' isn't a function or method and can't be invoked.

setter正确调用方式

无论在类内部还是外部,调用setter都要使用赋值语句的形式,和给普通变量赋值的写法完全一致,不需要用括号传递参数。
将原构造函数的代码修改为如下形式即可正常运行:

Cat(String initialSize, String initialColor, int initialAge) {
   size = initialSize;
   color = initialColor;
   age = initialAge;
}

代码优化建议

Dart提供了更简洁的构造函数语法,如果setter中没有额外的参数校验、属性转换逻辑,可以直接用初始化语法糖完成私有属性赋值,代码更精简:

class Cat {
  String _size = '';
  String _color = '';
  int _age = 0;

  // 构造函数语法糖直接完成私有属性初始化
  Cat(this._size, this._color, this._age);

  String get size => _size;
  void set size(String animalSize) => _size = animalSize;

  String get color => _color;
  void set color(String animalColor) => _color = animalColor;

  int get age => _age;
  void set age(int animalAge) => _age = animalAge;
}

调用注意事项

  • setter无返回值,调用时只能出现在赋值操作的左侧
  • 类内部调用setter无需额外加this.前缀,仅当存在同名局部变量产生命名冲突时才需要加前缀明确指向
  • 不要使用函数调用的括号语法传参调用setter,这是Dart和部分面向对象语言的语法差异点

内容的提问来源于stack exchange,提问作者Sardorbek

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.29 18:22:47