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

Dart类中getter与setter类型不匹配问题求助

Dart Getter与Setter类型不匹配错误修复

错误原因

你的description getter返回类型是String?(可空),但对应的setter参数类型是String(非空),Dart要求同一个属性的getter返回类型和setter参数类型必须一致,这就是报错的核心原因。另外你的date setter还存在变量赋值错误。

修复步骤

  1. 统一description的setter类型
    将description setter的参数类型改为String?,同时添加null判断避免调用null.length报错:

    set description(String? newDescription) {
      if (newDescription == null || newDescription.length <= 255) {
        this._description = newDescription;
      }
    }
    
  2. 修正date setter的赋值错误
    原代码中date setter错误地给_description赋值,改为给_date赋值:

    set date(String newDate) {
      this._date = newDate;
    }
    

完整修正代码

class Note {
  late int _id;
  late String _title;
  late String? _description;
  late String _date;
  late int _priority;

  Note(this._title, this._date, this._priority, [this._description]);
  Note.withId(this._id, this._title, this._date, this._priority,
      [this._description]);

  // Getters
  int get id => _id;
  String get title => _title;
  String? get description => _description;
  String get date => _date;
  int get priority => _priority;

  // Setters
  set title(String newTitle) {
    if (newTitle.length <= 255) {
      this._title = newTitle;
    }
  }

  set description(String? newDescription) {
    if (newDescription == null || newDescription.length <= 255) {
      this._description = newDescription;
    }
  }

  set date(String newDate) {
    this._date = newDate;
  }

  set priority(int newPriority) {
    if (newPriority >= 1 && newPriority <= 2) {
      this._priority = newPriority;
    }
  }
}

关键注意点

当类成员变量声明为可空类型时,对应的getter和setter必须保持类型一致:

  • 如果允许属性被设为null,getter返回可空类型,setter参数也用可空类型
  • 如果不允许属性为null,成员变量就不要声明为可空类型,getter和setter都用非空类型

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 06:15:43