Flutter进阶:自定义一个 json 转 model 工具

289 阅读1分钟

一、需求来源

新项目中生成模型的工具用的乱七八糟,不知道什么野路子。随想自己实现一个,方便后面代码重构。

典型问题如下:

1、字段未做可空处理
String identifier;
或者
late String identifier;

2、fromJson 转换方法 cast 报警告
Results.fromJson 转换方法(Map<String, dynamic> json) { 
    supportedDevices = json['supportedDevices'].cast<String>();
}

3、其他一些有警告未处理代码

成果:

  1. 修复以上问题。
  2. 还支持 CopyWith 方法。
  3. 支持模型文件下载。
  4. 支持黑夜模式,护眼更佳。

二、运行效果

截屏2025-10-04 21.41.22.png

截屏2025-10-04 21.41.15.png

最后、成功

JsonToModel