Ashish Yadav
Ashish Yadav

Reputation: 543

unable to get user location when the app starts in flutter

I want to get user location when the app starts. This code runs fine when I already have the location enabled before starting the app and then I start the the app. But when it is disabled and then start the app, I am unable to get the location.

Below is what the snippet looks like:

Future<void> _isLocationEnabled() async {
_serviceEnabled = await location.serviceEnabled();
if (!_serviceEnabled) {
  _serviceEnabled = await location.requestService();
  if (!_serviceEnabled) {
    setState(() {
      _isLoading = false;
    });
    showModalBottomSheet(
        //showing modal sheet here 
        });
  } else {
    try {
      locationData = await Location().getLocation();
    } catch (e) {
      print(e);
    }

    setState(() {
      _isLoading = false;
    });
  }
} else {
  locationData = await Location().getLocation();
  setState(() {
    _isLoading = false;
  });
}
_permissionGranted = await location.hasPermission();
if (_permissionGranted == PermissionStatus.denied) {
  _permissionGranted = await location.requestPermission();
  if (_permissionGranted != PermissionStatus.granted) {
    return;
  }
}

}

The thing is that the catch block doesnt run nor I am able to get the location. I call this function in initState like this:

@override
  void initState() {
    super.initState();
    _isLocationEnabled();
  } 

Is there something I am missing?

Upvotes: 0

Views: 138

Answers (1)

Laxmikanth Madhyastha
Laxmikanth Madhyastha

Reputation: 342

I had a similar issue, try to get the location after a delay.

The below code should do the trick

Future<void> _isLocationEnabled() async {
    _serviceEnabled = await location.serviceEnabled();
    if (!_serviceEnabled) {
      _serviceEnabled = await location.requestService();
      if (!_serviceEnabled) {
        setState(() {
          _isLoading = false;
        });
        showModalBottomSheet(
            //showing modal sheet here
            );
      } else {
        try {
          Future.delayed(Duration(seconds: 1), () async {
            locationData = await Location().getLocation();
            print(locationData);
          });
        } catch (e) {
          print(e);
        }

        setState(() {
          _isLoading = false;
        });
      }
    } else {
      locationData = await Location().getLocation();
      setState(() {
        _isLoading = false;
      });
    }
    _permissionGranted = await location.hasPermission();
    if (_permissionGranted == PermissionStatus.denied) {
      _permissionGranted = await location.requestPermission();
      if (_permissionGranted != PermissionStatus.granted) {
        return;
      }
    }
  }

Upvotes: 2

Related Questions