我正在尝试获取用户的经度和纬度坐标,但在从Future访问这些值时遇到了问题。
目前,我正在使用Geolocator包来获取Future,但在检索该值时遇到错误。
为了获取位置,我正在做以下操作:
Future<Position> locateUser() async {
return Geolocator()
.getCurrentPosition(desiredAccuracy: LocationAccuracy.high)
.then((location) {
if (location != null) {
print("Location: ${location.latitude},${location.longitude}");
}
return location;
});
}为了在build Widget函数中检索这些坐标,我执行以下操作:
bool firstTime = true;
String latitude;
String longitude;
@override
Widget build(BuildContext context) {
if(firstTime == true) {
locateUser().then((result) {
setState(() {
latitude = result.latitude.toString();
longitude = result.longitude.toString();
});
});
fetchPost(latitude, longitude);
firstTime = false;
}我得到的错误是:
[VERBOSE-2:ui_dart_state.cc(148)] Unhandled Exception: Invalid argument(s)我希望能够将那些协调好的变量存储在变量中,并将它们传递给我拥有的其他函数。我是Flutter的新手,所以任何帮助都将不胜感激!
发布于 2019-04-16 03:45:03
您使用的是async方法,因此可以使用await关键字来获取响应:
改变这一点
Future<Position> locateUser() async {
return Geolocator()
.getCurrentPosition(desiredAccuracy: LocationAccuracy.high)
.then((location) {
if (location != null) {
print("Location: ${location.latitude},${location.longitude}");
}
return location;
});
}要这样做:
Future<Position> locateUser() async {
final location = await Geolocator().getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
if (location != null) {
print("Location: ${location.latitude},${location.longitude}");
}
return location;
}在你的回调中调用fetchPost(latitude, longitude),从build方法中移除你的调用,转移到initState方法上,或者你也可以使用FutureBuilder。
@override
void initState() {
locateUser().then((result) {
setState(() {
latitude = result.latitude.toString();
longitude = result.longitude.toString();
fetchPost(latitude, longitude);
});
});
super.initState();
}https://stackoverflow.com/questions/55696199
复制相似问题