flutter - 在颤振中将纬度和经度传递给Latlng时出错
问题描述
我正在尝试重构我的代码并将 showMap 类分离到一个新的 dart 文件中。我正在从调用此类的屏幕向 showMap 传递纬度和经度。我检查过这里的纬度和经度不为空。但我收到一条错误消息:
The following NoSuchMethodError was thrown building showMap(dirty): The method 'compareTo' was called on null. Receiver: null Tried calling: compareTo(-90.0)
class showMap extends StatelessWidget {
showMap({this.latitude, this.longitude});
double latitude;
double longitude;
@override
Widget build(BuildContext context) {
return FlutterMap(
options: MapOptions(
center: LatLng(latitude, longitude), // The Error line
zoom: 16.0,
),
layers: [
TileLayerOptions(
urlTemplate: "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
subdomains: ['a', 'b', 'c']),
MarkerLayerOptions(
markers: [
Marker(
width: 80.0,
height: 80.0,
point: LatLng(58.7041, 37.1025),
builder: (ctx) => GestureDetector(
child: Container(
child: Icon(
Icons.location_on,
size: 60,
color: Color(0xFF744D81),
),
),
onTap: () {
showModalBottomSheet(
context: context,
builder: (context) {
return MarkerPopup();
});
},
),
),
Marker(
width: 80.0,
height: 80.0,
point: LatLng(58.4419, 37.0784),
builder: (ctx) => GestureDetector(
child: Container(
child: Icon(Icons.location_on,
size: 60, color: Color(0xFF744D81)),
),
onTap: () {
showModalBottomSheet(
context: context,
builder: (context) {
return MarkerPopup();
});
},
),
),
],
),
],
);
}
}
这是调用 showMap 的代码部分:
class _HomePageState extends State<HomePage> {
void getLocation() async {
Location location = Location();
await location.getCurrrentLocation();
latitude = location.latitude;
longitude = location.longitude;
}
@override
void initState() {
super.initState();
getLocation();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Udan'),
backgroundColor: Color(0xFF4E295B),
centerTitle: true,
),
body: Stack(
children: <Widget>[
showMap(
latitude: latitude,
longitude: longitude,
),
],
),
);
}
}
奇怪的是,一两秒钟后,错误消失了,地图被加载到了正确的中心。但与此同时,代码中断并且屏幕显示错误。我猜这是因为获取位置需要时间,并且传递纬度和经度的空值,直到获取位置。在将值分配给 showMap 之前,我已经在原始屏幕中使用了异步等待。我怎样才能让它工作?谢谢。
解决方案
getLocation 方法包含一个异步操作,并且 build 方法在它解析之前执行。
一个选项可能是在纬度和经度为空时显示加载器。一旦未来的 location.getCurrrentLocation 得到解决,您就可以调用 showMap。
推荐阅读
- javascript - 在 Blazor 应用程序中使用 Jquery 函数而无需单击按钮
- php - 未为自定义路由发送验证电子邮件获取未定义路由 [verification.verify]
- angular - 在 Angular Material 自定义对话框中显示组件
- r - 在 sparklyr 中汇总标准偏差并计算非 NA
- python - 根据列中的值列表和数字过滤行
- sql-server - 检查列值是否更新为 NULL
- visual-studio - 方法参考弹窗不可读
- php - 如何将此“create_function”调用转换为匿名函数?
- python - 在不创建组合产品的情况下取消嵌套 Pandas 系列
- javascript - 如何在axios中使用png响应在react中获取请求