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

解决Dart中Note类无命名构造函数缺失的报错问题

解决Dart中"The class 'Note' doesn't have an unnamed constructor"报错

你在调用navigateToDetail(Note('','',2), "add Note")时触发该报错,原因是当前Note类仅定义了命名构造函数Note.withId和Note.fromMapObject,缺少无命名的默认构造函数,而你调用的Note('','',2)正是在尝试使用无命名构造函数。

解决方案:添加匹配调用参数的无命名构造函数

根据你传入的三个参数(两个字符串、一个整数),对应Note类的_title、_date、_priority属性,同时将_id设为null(新增笔记时id通常由数据库生成),_description设为可选参数默认空字符串。修改后的Note类代码如下:

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

  // 添加无命名构造函数,匹配你的调用参数
  Note(this._title, this._date, this._priority, [this._description = '']) : _id = null;
  
  Note.withId(this._id, this._title, this._date, this._priority, [this._description = '']);

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

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

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

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

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

  Map<String, dynamic> toMap() {
    var map = Map<String, dynamic>();
    if (id != null) {
      map['id'] = _id;
    }
    map['title'] = _title;
    map['description'] = _description;
    map['priority'] = _priority;
    map['date'] = _date;
    return map;
  }

  Note.fromMapObject(Map<String, dynamic> map)
      : _id = map['id'],
        _title = map['title'],
        _date = map['date'],
        _priority = map['priority'],
        _description = map['description'];
}

说明

  • 添加的无命名构造函数Note(this._title, this._date, this._priority, [this._description = '']) : _id = null;完全匹配你调用Note('','',2)的参数结构:前三个必填参数对应标题、日期、优先级,第四个为可选的描述(默认空字符串),同时初始化_id为null(符合新增笔记时id未生成的场景)。
  • 构造函数后的: _id = null是初始化列表,用于初始化未在参数列表中直接赋值的属性。

修改后,你原来的调用代码Note('','',2)就能正常创建Note对象,报错即可解决。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 08:12:41