Flutter Future always return null
What is wrong in my code it always returns null
getLocation().then((r) {
if (r != null) {
print("r=" + r.length.toString());
} else {
print("result is null");
}
});
Future< List<double>> getLocation() async {
// print("getLocation called");
location = new Location();
List<double> result=[];
location.getLocation().then((loc) {
result.add(loc.latitude);
result.add(loc.longitude);
result.add(4213);
// print(loc.latitude.toString() + "," + loc.longitude.toString() +" l="+l1.length.toString());
return result;
}).catchError((e){
return result;
});
}
Solution 1:
You are not returning anything in your function, only in your then
callback.
Since you are using async syntax anyway you can just go for:
Future< List<double>> getLocation() async {
location = new Location();
List<double> result=[];
var loc = await location.getLocation();
result.add(loc.latitude);
result.add(loc.longitude);
result.add(4213);
return result;
}
I've taking error handling out of the code but you can just use try-catch if you want that.