GTF
GTF

Reputation: 155

Flutter position exception with geolocator

I'm new in flutter and I want to build a basic app in which I have to retrieve the position and based on the position I have to show different Item.

I tried to retrieve position by using of Geolocator, and it works, my problem is when I have to manage the exception.

For example when user reject permission I have to show an error, also when I have the permission but the service is disabled I have to show an other error.

If user have the service disabled and after he active it I have to reload the page and the error have to disappear.

How I can handle these cases?

that's my simple code:

import 'package:flutter/material.dart';
import 'package:geocoding/geocoding.dart';
import 'package:geolocator/geolocator.dart';
import 'package:location/location.dart' as loc;

class LocationPage extends StatefulWidget {
  @override
  _LocationPageState createState() => _LocationPageState();
}

class _LocationPageState extends State<LocationPage> {
  Position _currentPosition;
  bool serviceEnabled = false;
  @override
  void initState() {

    getLocationPermission();
      _getCurrentLocation();
    super.initState();
  }

  getLocationPermission() async {

    if (!await locationR.serviceEnabled()) {
      setState(() async {
        serviceEnabled = await locationR.requestService();
        if(serviceEnabled){
          _getCurrentLocation();
        }
      });

    } else {
      setState(() {
        serviceEnabled = true;
      });
    }

  }

  String _currentAddress;
  loc.Location locationR = loc.Location();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Location"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            _currentAddress != null ? Text(_currentAddress) : serviceEnabled ? Loading() : Text("Errors"),
          ],
        ),
      ),
    );
  }

  _getCurrentLocation() {
    Geolocator.getCurrentPosition(
            desiredAccuracy: LocationAccuracy.best,
            forceAndroidLocationManager: true)
        .then((Position position) {
      setState(() {
        _currentPosition = position;
        _getAddressFromLatLng(_currentPosition);
      });
    }).catchError((e) {
      print(e);
    });
  }

  _getLastPosition() {
    Geolocator.getLastKnownPosition().then((Position position) {
      setState(() {
        _currentPosition = position;
        _getAddressFromLatLng(_currentPosition);
      });
    }).catchError((e) {
      print(e);
    });
  }

  _getAddressFromLatLng(Position position) async {
    try {
      List<Placemark> placemarks =
          await placemarkFromCoordinates(position.latitude, position.longitude);

      Placemark place = placemarks[0];

      setState(() {
        _currentAddress =
            "${place.locality}, ${place.postalCode}, ${place.country},${place.toString()}";
      });
    } catch (e) {
      print(e);
    }
  }
}

thank's all

Upvotes: 0

Views: 3349

Answers (1)

Jaime Ortiz
Jaime Ortiz

Reputation: 1309

You can check for the possible results from the checkPermission and requestPermission methods, which are denied, deniedForever, whileInUse and forever.

Here's an example on how to acquire the current position of the device, including checking if the location services are enabled and checking / requesting permission to access the position of the device:

import 'package:geolocator/geolocator.dart';

/// Determine the current position of the device.
///
/// When the location services are not enabled or permissions
/// are denied the `Future` will return an error.
Future<Position> _determinePosition() async {
  bool serviceEnabled;
  LocationPermission permission;

  // Test if location services are enabled.
  serviceEnabled = await Geolocator.isLocationServiceEnabled();
  if (!serviceEnabled) {
    // Location services are not enabled don't continue
    // accessing the position and request users of the 
    // App to enable the location services.
    return Future.error('Location services are disabled.');
  }

  permission = await Geolocator.checkPermission();
  if (permission == LocationPermission.denied) {
    permission = await Geolocator.requestPermission();
    if (permission == LocationPermission.denied) {
      // Permissions are denied, next time you could try
      // requesting permissions again (this is also where
      // Android's shouldShowRequestPermissionRationale 
      // returned true. According to Android guidelines
      // your App should show an explanatory UI now.
      return Future.error('Location permissions are denied');
    }
  }
  
  if (permission == LocationPermission.deniedForever) {
    // Permissions are denied forever, handle appropriately. 
    return Future.error(
      'Location permissions are permanently denied, we cannot request permissions.');
  } 

  // When we reach here, permissions are granted and we can
  // continue accessing the position of the device.
  return await Geolocator.getCurrentPosition();
}

Upvotes: 4

Related Questions