带有地理定位器的颤动位置异常
Flutter position exception with geolocator
我是 flutter 的新手,我想构建一个基本的应用程序,我必须在其中检索位置并根据位置显示不同的项目。
我尝试使用 Geolocator 检索位置,它起作用了,我的问题是当我必须管理异常时。
例如,当用户拒绝权限时我必须显示错误,当我有权限但服务被禁用时我必须显示其他错误。
如果用户禁用了该服务并在他激活它后我必须重新加载页面并且错误必须消失。
我该如何处理这些情况?
这是我的简单代码:
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);
}
}
}
谢谢大家
您可以检查 checkPermission
和 requestPermission
方法的可能结果,即 denied
、deniedForever
、whileInUse
和 [=16] =].
这里举例说明如何获取设备的当前位置,包括检查定位服务是否启用以及检查/请求访问设备位置的权限:
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();
}
我是 flutter 的新手,我想构建一个基本的应用程序,我必须在其中检索位置并根据位置显示不同的项目。
我尝试使用 Geolocator 检索位置,它起作用了,我的问题是当我必须管理异常时。
例如,当用户拒绝权限时我必须显示错误,当我有权限但服务被禁用时我必须显示其他错误。
如果用户禁用了该服务并在他激活它后我必须重新加载页面并且错误必须消失。
我该如何处理这些情况?
这是我的简单代码:
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);
}
}
}
谢谢大家
您可以检查 checkPermission
和 requestPermission
方法的可能结果,即 denied
、deniedForever
、whileInUse
和 [=16] =].
这里举例说明如何获取设备的当前位置,包括检查定位服务是否启用以及检查/请求访问设备位置的权限:
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();
}