gpt4 book ai didi

flutter - flutter 的正确方法来处理多个类中的Future(Google Maps)

转载 作者:行者123 更新时间:2023-12-03 03:58:20 25 4
gpt4 key购买 nike

我有一个模型课

LocalInfo.dart

class LocationInfo {
// LocationController
Location location = Location();

//Location Position Data
LocationData currentLocation;
double longitude;
double latitude;

LocationInfo() {
try {
location.getLocation().then((location) {
currentLocation = location;
longitude = currentLocation.longitude;
latitude = currentLocation.latitude;
});
} catch (e) {
currentLocation = null;
}
}
}

和我的Maps类MapsService.dart
MapsService() {
loading = true;
locationInfo = LocationInfo(); // <== This takes some time
cameraPosition = CameraPosition(
zoom: 15,
target: LatLng(locationInfo.latitude, locationInfo.longitude)); // <-- Latitude Longitude is null
loading = false;
}

这里的问题是我创建了一个具有经度和纬度作为类成员的LocationInfo Model对象。但是,由于location.getLocation()返回Future,因此需要花费一些时间。

但是,在我的MapsService类中,我创建了LocationInfo对象,并将cameraPosition设置为给定的纬度和经度。但是如何等待经度和纬度值? Long / Lat为null并由于我不等待而使应用程序崩溃。

我需要MapService构造函数中的一种方法来等待LocationInfo。必须先设置纬度和经度值才能完成

最佳答案

您不能只在模型中使用外部API。 ModelClass只是一个数据。您只需要在应用程序的某个位置启动订阅,只需更新与 map 小部件关联的数据即可

理想情况下,您需要这样的东西:

LocationInfo userPosition;
StreamSubscription<LocationData> positionSubscription;

@override
void initState() {
super.initState();
positionSubscription = location
.onLocationChanged()
.handleError((error) => print(error))
.listen(
(newPosition) => setState(() {
_currentLocation = LocationInfo(
latitude: newPosition.latitude,
longitude: newPosition.longitude,
);
}),
);
}

@override
void dispose() {
positionSubscription?.cancel();
super.dispose();
}

@override
Widget build(BuildContext context) {
return MapWidget(userPosition);
}

关于flutter - flutter 的正确方法来处理多个类中的Future(Google Maps),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59410565/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com