Home > OS >  Flutter how to use async return value from a function
Flutter how to use async return value from a function

Time:10-23

I'm new to flutter, I just want to ensure if the below code is correct, I want to check if the location permission was granted or no, if yes then get the current location and save into shared preferences and THEN go to the homepage route, otherwise go to the location page to ask the user for access his location

@override
void initState() {
  super.initState();
  checkLocation(context);
}



  void checkLocation(context) async {
    bool isGranted = await asyncFunction();
    if(isGranted)
    {
      updateSettingLocation();
      Navigator.of(context).pushNamed('/homepage');
    } else{
      Navigator.of(context).pushNamed('/location');
    }
  }
  void updateSettingLocation() async{
    final location = await currentLocation();
    settingsRepo.setCurrentLocation(location);
  }

  Future<Position> currentLocation() {
    return Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high)
        .then((location) {
      if (location != null) {
        print("Location: ${location.latitude},${location.longitude}");
      }
      return location;
    });
  }

  void updateCurrentLocation() async {
    Position position = await Geolocator.getCurrentPosition(
        desiredAccuracy: LocationAccuracy.high);
    settingsRepo.setCurrentLocation(position);
  }


  Future<bool> asyncFunction() async {
    bool serviceEnabled;
    LocationPermission permission;
    permission = await Geolocator.checkPermission();
    serviceEnabled = await Geolocator.isLocationServiceEnabled();
    if (permission == LocationPermission.denied || !serviceEnabled || permission == LocationPermission.deniedForever) {
      print('location access is denied');
      return false;
    } else {
      print('location access is granted');
      return true;
    }
  }

CodePudding user response:

As mentioned in this Stack Overflow answer , the following changes should sufficient

@override
void initState() {
  super.initState();
  WidgetsBinding.instance.addPostFrameCallback((_) => checkLocation(context));
}

Though I would like to point out that context is not available in initState (unless it's a variable that you've created and are managing)

CodePudding user response:

All the functions defined are correct and the methodology is also fine. It should work with no issues. However I would suggest instead of defining all the functions here in the widget class you should separate it out from the UI by creating a separate class (Example: LocationService) and then initialize that class here and then make use of the functions.

  • Related