writeModelToFile<T> static method
将单个对象写入 JSON 文件
model 要写入的对象
filePath 保存到的文件路径
toJson 对象转换为 Map 的函数
返回值: bool 是否写入成功(true成功,false失败)
使用示例:
WheelModel model = WheelModel(...);
bool ok = JsonUtil.writeModelToFile<WheelModel>(
model,
'/tmp/wheel.json',
(m) => m.toJson(),
);
print(ok);
Implementation
static bool writeModelToFile<T>(
T model,
String filePath,
Map<String, dynamic> Function(T) toJson,
) {
try {
final file = File(filePath);
file.parent.createSync(recursive: true);
final jsonMap = toJson(model);
final jsonString = jsonEncode(jsonMap);
file.writeAsStringSync(jsonString);
return true;
} catch (e) {
Logger.log('Error writing model to file: $e');
return false;
}
}