#android #ios #flutter #geolocation
Вопрос:
Я новичок в flutter и хочу создать базовое приложение, в котором я должен извлекать позицию и на основе позиции показывать другой элемент.
Я попытался получить местоположение с помощью геолокатора, и это работает, моя проблема в том, что мне приходится управлять исключением.
Например, когда пользователь отклоняет разрешение, я должен показать ошибку, также когда у меня есть разрешение, но служба отключена, я должен показать другую ошибку.
Если у пользователя отключена служба, и после того, как он активирует ее, я должен перезагрузить страницу, и ошибка должна исчезнуть.
Как я могу справиться с этими делами?
это мой простой код:
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);
}
}
}
спасибо всем
Комментарии:
1. Привет, моя ситуация немного сложнее, чем ваша, потому что мне нужно фоновое местоположение. И у меня нет времени давать вам более полный ответ. В моем случае я использовал этот плагин, посмотрите, поможет ли это. pub.dev/пакеты/location_permissions
Ответ №1:
Вы можете проверить возможные результаты с checkPermission
requestPermission
помощью методов и, которые являются denied
, deniedForever
, whileInUse
и forever
.
Вот пример того, как получить текущее местоположение устройства, включая проверку того, включены ли службы определения местоположения, и проверку / запрос разрешения на доступ к местоположению устройства:
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();
}