Home > Back-end >  Future is stuck on return statement and never completes the function future called from
Future is stuck on return statement and never completes the function future called from

Time:12-31

getInitialTripData calls getCurrentLocationData with await but it never prints "coming here 1" and on getCurrentLocationData the function goes on till printing the data and then stuck on return statement i dont know what the issue is

setInitialTripData() async {
    print("coming here");
    MapLocation startingPoint=await Get.find<LocationService>().getCurrentLocationData();
    print("coming here 1");
      if (startingPoint != null) {
        tripData.startingPoint = startingPoint;
        startingPointTextController.text = startingPoint.name;
        update();
      }
  }

Future<MapLocation> getCurrentLocationData()async{
   try{
     if(!locationAllowed.value){
       return null;
     }
     LocationData position=await _location.getLocation();
     List<geo.Placemark> placemark =
     await geo.placemarkFromCoordinates(position.latitude, position.longitude);
     if(placemark.length==0 || placemark==null){
       return null;
     }
     MapLocation mapLocation=MapLocation(name: "${placemark[0].name.isNotEmpty? placemark[0].name ", ":""}${placemark[0].subAdministrativeArea.isNotEmpty? placemark[0].subAdministrativeArea ", ":""}${placemark[0].isoCountryCode.isNotEmpty? placemark[0].isoCountryCode:""}",latitude: position.latitude,longitude: position.longitude);
    print(mapLocation.getDataMap());
     return mapLocation;
   }
   catch(e){
     return null;
   }
  }

CodePudding user response:

getCurrentLocation has a bunch of chances to return null, and you're not handling a potential null return value in setInitialTripData

your code only continues executing if startingPoint != null it seems.

CodePudding user response:

Well Problem is in your getCurrentLocationData function because your function is expecting a return value of type MapLocation because you have declared in your function it's return type here

Future<MapLocation> getCurrentLocationData(){}

That's why when you return null from this function this throws an error and break your functions.

What you need to do is either remove return type or make it nullable whichever works fine like :

Future<MapLocation?> getCurrentLocationData(){}

Or

Future getCurrentLocationData(){}

Apart from that you need to make the receiving variable nullable so that it can handle null data

MapLocation? startingPoint=await Get.find<LocationService>().getCurrentLocationData();
  • Related