Flutter中为Google Maps Marker设置经纬度及解决空值问题
Google Maps Marker position参数传入与空值问题解决
问题描述
我正在尝试为Google Maps的Marker类型的position参数添加经纬度值,已获取对应值但不知如何正确传入参数。
最初的错误代码:
position: LatLng(PropertyInformation.fromJson(i).latitude + "," + PropertyInformation.fromJson(i).longitude),
已知该写法错误,因为将double类型当作字符串拼接,而LatLng定义要求传入(double latitude, double longitude)类型参数,请问正确传入方式是什么?
之后尝试如下代码,却出现空值错误:
position: LatLng(double.tryParse(PropertyInformation.fromJson(i).latitude) ?? 0.0 , double.tryParse(PropertyInformation.fromJson(i).longitude) ?? 0.0)
鼠标悬停在.latitude上时出现空值相关错误提示,该如何解决这个空值类型问题?
解决方案
1. 正确传入LatLng参数的基础写法
LatLng构造函数需要两个独立的double类型参数(纬度在前、经度在后),无需拼接成字符串。如果PropertyInformation.fromJson(i).latitude和.longitude本身就是非空double类型,直接传入即可:
position: LatLng( PropertyInformation.fromJson(i).latitude, PropertyInformation.fromJson(i).longitude ),
2. 解决空值错误问题
空值提示说明PropertyInformation.fromJson(i).latitude/.longitude是可空类型(double?或String?),需针对性处理:
情况1:经纬度是可空double类型
如果字段在PropertyInformation中定义为double?,直接用空合并运算符指定默认值即可:
position: LatLng( PropertyInformation.fromJson(i).latitude ?? 0.0, PropertyInformation.fromJson(i).longitude ?? 0.0 ),
情况2:经纬度是可空String类型
如果字段是String?类型,先给空字符串兜底避免double.tryParse传入null报错,再处理转换失败的情况:
final property = PropertyInformation.fromJson(i); position: LatLng( double.tryParse(property.latitude ?? "") ?? 0.0, double.tryParse(property.longitude ?? "") ?? 0.0 ),
额外优化:避免重复解析JSON
当前代码多次调用PropertyInformation.fromJson(i)会重复解析JSON对象,建议先解析一次赋值给变量再使用,提升性能:
final property = PropertyInformation.fromJson(i); position: LatLng( property.latitude ?? 0.0, property.longitude ?? 0.0 ),
内容的提问来源于stack exchange,提问作者LostTexan
相关产品推荐
相关产品推荐

