颤振 - 来自不同类的异步函数打印正常,但返回 null



下面的函数在从main.dart调用时打印正确的值,但返回null。似乎该函数在返回之前不知何故没有等待值。

将不胜感激。

位置.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);
}
}
}

最新更新