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