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

GetStorage存储Mesure模型报对象无法转可编码对象错误修复

问题1:debut、fin字段不存在时是否可以跳过序列化

可以。Dart 序列化逻辑(包括GetStorage内置的对象编码流程)只会处理toJson()返回Map中包含的键值对,不需要序列化的字段只要不加入返回的Map,就会自动跳过,不会触发字段访问,也不会产生异常。

问题2:序列化报错修复方案

报错根因

  1. toJson()分支逻辑写反
    你的需求是mode值为display时才追加debut、fin字段,但现有代码逻辑完全颠倒:mode == "display"分支的返回值未包含这两个字段,非display分支反而强制返回这两个字段。而非display模式下,Mesure.init构造方法没有对late修饰的debut字段做初始化,未赋值的非空字段被访问时会触发运行时错误,最终被序列化框架捕获后抛出对象无法编码的异常。
  2. fromJson()未兼容字段缺失场景
    非display模式下序列化生成的Map本身没有debut、fin键,反序列化时直接读取json['debut']/json['fin']会得到null,赋值给非空String类型字段会触发类型错误。
  3. GetStorage调用方式错误
    GetStorage不会自动调用自定义类的toJson()方法,如果直接传入Mesure类实例做写入操作,会直接抛出你遇到的Converting object to an encodable object failed: Instance of 'Mesure'异常。

修复步骤

  • 调整字段定义,去掉debut、fin的late修饰,给定默认空值,避免未初始化问题
  • 修正toJson()逻辑,仅在mode为display时追加debut、fin字段
  • 给fromJson()的字段读取增加空值兼容,缺省值取空字符串
  • 写入GetStorage时手动调用toJson()转成Map类型后再存储

修复后的Mesure类代码如下:

class Mesure {
  late int id;
  String status;
  late String mode;
  late String equipementNumero;
  late String temperature;
  late String courant = "";
  String debut = "";
  String fin = "";

  Mesure.init(List<String> values, this.id, this.status) {
    mode = values[0];
    equipementNumero = values[1];
    temperature = values[2];
    courant = values[3];

    if (mode == "display") {
      debut = values[4];
      fin = values[5];
    }
  }

  Mesure.fromJson(Map<String, dynamic> json)
      : id = json['id'],
        status = json['status'],
        mode = json['mode'],
        temperature = json['temperature'],
        equipementNumero = json['equipementNumero'],
        courant = json['courant'] ?? "",
        debut = json['debut'] ?? "",
        fin = json['fin'] ?? "";

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> baseData = {
      'id': id,
      'status': status,
      'mode': mode,
      'temperature': temperature,
      'equipementNumero': equipementNumero,
      'courant': courant,
    };
    if (mode == "display") {
      baseData['debut'] = debut;
      baseData['fin'] = fin;
    }
    return baseData;
  }
}

GetStorage读写参考:

// 写入:必须手动转Map
final box = GetStorage();
await box.write('mesure_${mesure.id}', mesure.toJson());

// 读取:拿到Map后通过fromJson转模型
final storedMap = box.read('mesure_${targetId}');
final storedMesure = Mesure.fromJson(storedMap);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 01:39:19