Dart开启空安全后默认List构造器不可用报错如何处理?
报错原因
Dart 2.12及以上版本启用空安全后,默认无参数List()构造器已被正式移除,该构造器原本用于创建可增长的空列表,你的代码中coordinates = new List<List>();的写法不符合空安全规范,因此触发报错。
另外你的现有代码还存在两个隐性问题:
- 泛型定义不明确,
List<List>没有指定内层List的元素类型 - 调用
List.fromJson(v)属于错误写法,Dart原生List类不存在fromJson构造器
修复方案
分两种常用场景提供修复代码:
场景1:coordinates是嵌套数值数组(标准GeoJSON结构)
如果你的坐标是[[1.0, 2.0], [3.0,4.0]]这类嵌套数值结构,修复后代码如下:
class Geometry { // 可根据实际结构调整泛型,比如Polygon需要三层嵌套的话就改成List<List<List<num>>> List<List<num>> coordinates; String type; Geometry({required this.coordinates, required this.type}); Geometry.fromJson(Map<String, dynamic> json): coordinates = (json['coordinates'] as List).map((v) => List<num>.from(v)).toList(), type = json['type'] as String; Map<String, dynamic> toJson() { final Map<String, dynamic> data = <String, dynamic>{}; data['coordinates'] = coordinates.map((v) => v.toList()).toList(); data['type'] = type; return data; } }
场景2:coordinates内层是自定义实体类
如果内层元素是你自定义的坐标实体类,先补充对应实体类的定义,再修正序列化逻辑即可,示例如下:
// 先定义坐标实体类 class Coordinate { final num lat; final num lng; Coordinate({required this.lat, required this.lng}); Coordinate.fromJson(Map<String, dynamic> json): lat = json['lat'] as num, lng = json['lng'] as num; Map<String, dynamic> toJson() => {'lat': lat, 'lng': lng}; } // 修正后的Geometry类 class Geometry { List<Coordinate> coordinates; String type; Geometry({required this.coordinates, required this.type}); Geometry.fromJson(Map<String, dynamic> json): coordinates = (json['coordinates'] as List).map((v) => Coordinate.fromJson(v)).toList(), type = json['type'] as String; Map<String, dynamic> toJson() { final Map<String, dynamic> data = <String, dynamic>{}; data['coordinates'] = coordinates.map((v) => v.toJson()).toList(); data['type'] = type; return data; } }
核心修改点说明
- 移除所有废弃的
new List()写法,改用字面量或者List.from/List.map直接生成目标类型列表 - 明确List的泛型类型,避免动态类型带来的运行时风险
- 改用初始化列表的方式实现
fromJson构造,避免late关键字带来的未初始化风险 - 移除不必要的
new关键字,符合Dart最新的语法规范
内容的提问来源于stack exchange,提问作者Giovanni
相关产品推荐
相关产品推荐

