Home > OS >  can't return from condition block
can't return from condition block

Time:01-18

Here am trying to return a Position type from a function inside a condition statement but am getting a runtime error that the function is not returning a of Position type.

 Future<Position> getCurrentDevicePosition(BuildContext context) async {
    if (await checkLocationService(context)) {
      if (await checkPermission(context) == LocationPermission.always) {
        return await Geolocator.getCurrentPosition();
      }
    }
    
  }

CodePudding user response:

So i solved the problem just by adding "?" to the return type of the function like so but i don't know if that is possible with java too because i had such experience with java and I did not finish it... here is how i did it using Dart in flutter.

Future<Position?> getCurrentDevicePosition(BuildContext context) async {
    if ((await checkLocationService(context)) &&
        (await checkPermission(context) == LocationPermission.always)) {
      return Geolocator.getCurrentPosition();
    } else {
      errorSnackBar(context, 'Location enable location');
    }
    return null;
  }

CodePudding user response:

You don't need return await if you return type is Future<Position>. Just use

return Geolocator.getCurrentPosition();

await goes in the other place:

Position position = await getCurrentDevicePosition(context);
  • Related