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

修改JSON文件numberOfEvents与recordingTime值遇NoSuchMethodError问题

修改JSON文件字段值失败的解决方法

我尝试修改JSON文件中的numberOfEvents和recordingTime字段值,但操作失败,报错信息如下:

编辑说明:即便把JSON里的"numberOfEvents":0,改成"numberOfEvents":"0",,还是会出现相同错误:Class 'String' has no instance method 'add'.

错误日志:

E/flutter (25057): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: NoSuchMethodError: Class 'int' has no instance method 'add'.
E/flutter (25057): Receiver: 0
E/flutter (25057): Tried calling: add("0")
E/flutter (25057): #0      Object.noSuchMethod (dart:core-patch/object_patch.dart:38:5)

请问修改已有JSON中键值的最佳方法是什么?


JSON文件内容

{
"version":"1.0.0",
"numberOfEvents":0,
"recordingTime":"00:00:00",
"data":[{
       "data1": "data"
       ]}
}

现有Dart代码

static writeRecording(String numberOfEvents, String recordingtime) async {
  print("Writing to file the last info");
  final path = await _localPath;

  File file = File(path + filename2);
  var jsonObject = json.decode(file.readAsStringSync());


  jsonObject['numberOfEvents'].add(numberOfEvents);
  jsonObject['recordingTime'].add(recordingtime);
  file.writeAsString(json.encode(jsonObject), mode: FileMode.write);
}

问题原因

你用错了方法:add()是数组(List)专属的添加元素方法,但numberOfEvents和recordingTime都是单个值(int或String类型),根本不是数组,调用add()必然报错。你要做的是直接覆盖原字段的值,而非调用数组方法。

正确修改方案

直接赋值覆盖原字段,同时注意类型匹配:

  • numberOfEvents在JSON中是int类型,需要把传入的String参数转成int;
  • recordingTime本身就是String类型,直接赋值即可。

修改后的Dart代码:

static writeRecording(String numberOfEvents, String recordingtime) async {
  print("Writing to file the last info");
  final path = await _localPath;

  File file = File(path + filename2);
  var jsonObject = json.decode(file.readAsStringSync());

  // 直接赋值,处理类型转换
  jsonObject['numberOfEvents'] = int.parse(numberOfEvents);
  jsonObject['recordingTime'] = recordingtime;

  // 用await确保文件写入完成
  await file.writeAsString(json.encode(jsonObject), mode: FileMode.write);
}

额外注意事项

  1. 原JSON的data字段有语法错误,数组闭合符]应该放在对象闭合符}之后,正确格式:
"data": [{
       "data1": "data"
}]
  1. 如果传入的numberOfEvents可能是非法数字,建议加异常处理避免崩溃:
try {
  jsonObject['numberOfEvents'] = int.parse(numberOfEvents);
} catch (e) {
  // 转换失败时设置默认值
  jsonObject['numberOfEvents'] = 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 16:52:43