反向地理编码中Double与double类型赋值错误及模型问题求助
问题解决:反向地理编码中Address模型的类型与初始化错误
错误原因分析
- 类型不匹配:你在Address类中误用了大写的
Double类型,而Dart原生的浮点数值类型是小写的double。position.latitude返回的是Dart原生double,无法赋值给Double类型变量,直接触发类型不匹配报错。 - 可空性初始化异常:给变量添加
?标记为可空后,构造函数未正确处理参数规则——原代码中未加?的Double属于非空变量,必须在实例化时完成赋值,但你构造函数里的lattitude和longitude既没标记required,也没设置默认值,创建Address()实例时会违反Dart非空安全规则抛出异常。
修正方案
方案1:经纬度为必填字段(推荐)
如果地址必须包含经纬度,将类型改为原生double,并在构造函数中标记参数为required:
class Address { String? placeFormattedAddress; String? placeName; String? placeId; double latitude; // 修正为小写double double longitude; Address({ this.placeFormattedAddress, required this.latitude, // 标记必填 required this.longitude, // 标记必填 this.placeId, this.placeName, }); }
实例化时传入经纬度:
// 替换原创建实例的代码 Address userPickUpAddress = Address( latitude: position.latitude, longitude: position.longitude, ); userPickUpAddress.placeName = placeAddress;
方案2:经纬度为可选字段
如果允许地址不包含经纬度,将变量设为可空double?,构造函数参数无需required:
class Address { String? placeFormattedAddress; String? placeName; String? placeId; double? latitude; // 设为可空类型 double? longitude; Address({ this.placeFormattedAddress, this.latitude, this.longitude, this.placeId, this.placeName, }); }
此时原实例化代码Address userPickUpAddress = new Address();可正常运行,后续赋值经纬度也不会报错。
关键要点
- Dart原生数值类型均为小写(
int、double),避免混淆第三方库的大写包装类。 - 非空安全规则下,非空变量必须在实例化时完成初始化,要么通过
required构造参数,要么设置默认值;可空变量默认值为null,无需强制初始化。
内容的提问来源于stack exchange,提问作者Ronit Kataria
相关产品推荐
相关产品推荐

