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

Flutter中调用toJson方法时因Color类型引发序列化报错

解决Dart中Color类型的序列化与反序列化问题

方案一:存储Color的数值(推荐)

直接利用Color的value属性(整数类型)做序列化,这种方式比存字符串更高效且不易出错:

修改toJson方法:

Map<String, dynamic> toJson() {
  return {
    'id': id,
    'title': title,
    'detail': detail,
    'edittedOn': edittedOn.toString(),
    'color': color.value, // 存储Color对应的整数值
    'isLocked': isLocked,
  };
}

对应的fromJson方法:

factory Note.fromJson(Map<String, dynamic> map) {
  return Note(
    id: map['id'],
    title: map['title'],
    detail: map['detail'],
    edittedOn: DateTime.parse(map['edittedOn']), // 修正DateTime解析,还原存储的时间
    color: Color(map['color']), // 通过整数值重建Color对象
    isLocked: map['isLocked'],
  );
}

方案二:解析Color的字符串表示(兼容已存字符串数据)

如果已经用color.toString()存储了数据,字符串格式一般为Color(0xffxxxxxx)或Color(0xxxxxxxx),可以通过正则提取十六进制数值来重建Color:

先写一个辅助解析函数:

Color colorFromString(String colorStr) {
  // 匹配Color(0x...)格式的字符串,提取其中的十六进制部分
  final regex = RegExp(r'Color\(0x([0-9a-fA-F]+)\)');
  final match = regex.firstMatch(colorStr);
  if (match != null) {
    final hexValue = int.parse(match.group(1)!, radix: 16);
    return Color(hexValue);
  }
  // 解析失败时返回默认颜色,可根据需求调整
  return Colors.white;
}

再修改fromJson方法:

factory Note.fromJson(Map<String, dynamic> map) {
  return Note(
    id: map['id'],
    title: map['title'],
    detail: map['detail'],
    edittedOn: DateTime.parse(map['edittedOn']),
    color: colorFromString(map['color']), // 调用辅助函数解析字符串
    isLocked: map['isLocked'],
  );
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 03:43:19