[英]Flutter - Async function from a different class prints okay but returns null
从main.dart调用时,以下函数将打印正确的值,但返回null。 似乎该函数以某种方式不在返回之前等待该值。
希望能有所帮助。
location.dart
class Location {
StreamSubscription<Map<String, double>> _locationSubscription;
Future getLocation() async {
try{
geolocation.Location _location = new geolocation.Location();
_locationSubscription =
_location.onLocationChanged().listen((Map<String, double> result) {
print(result);
// This prints the proper value
return(result);
// But this returns null...
});
} on PlatformException {
return null;
} catch(e){
print(e);
}
}
}
主镖
@override
void initState(){
super.initState();
getLocation();
}
getLocation() async {
var location = Location();
var loc = await location.getLocation();
print(loc);
//This prints null
}
您必须定义未来的退货类型。
class Location {
StreamSubscription<Map<String, double>> _locationSubscription;
Future<Map<String, double>> getLocation() async {
try{
geolocation.Location _location = new geolocation.Location();
_locationSubscription =
_location.onLocationChanged().listen((Map<String, double> result) {
print(result);
// This prints the proper value
return(result);
// But this returns null...
});
} on PlatformException {
return null;
} catch(e){
print(e);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.