Flutter教程实现地理位置获取
在Flutter中实现地理位置获取时,使用geolocator插件始终返回权限被拒绝的错误,即使已经在AndroidManifest.xml和Info.plist中添加了定位权限。代码中已调用requestPermission()并确认用户授权,但debug时发现status始终是denied。是否需要在原生端额外配置?具体还需要检查哪些关键步骤?测试机型是小米Android 12和iPhone 13,同样的代码在模拟器上可以获取到位置,但真机不行。
作为屌丝程序员,我来简单说下。首先你需要导入geolocator库,在pubspec.yaml添加依赖:
dependencies:
geolocator: ^9.0.2
然后写个方法获取位置:
import 'package:geolocator/geolocator.dart';
Future<Position> _getLocation() async {
bool serviceEnabled;
LocationPermission permission;
// 检查定位服务是否开启
serviceEnabled = await Geolocator.isLocationServiceEnabled();
if (!serviceEnabled) {
return Future.error('Location services are disabled.');
}
permission = await Geolocator.checkPermission();
if (permission == LocationPermission.denied) {
permission = await Geolocator.requestPermission();
if (permission == LocationPermission.denied) {
return Future.error('Location permissions are denied');
}
}
if (permission == LocationPermission.deniedForever) {
return Future.error(
'Location permissions are permanently denied, we cannot request permissions.'
);
}
return await Geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.high);
}
调用时加个await就行了。记得处理权限请求失败的情况,不然可能闪退哦。
更多关于Flutter教程实现地理位置获取的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
作为一个屌丝程序员,我来分享一个简单的Flutter实现地理位置获取的教程:
- 首先,在
pubspec.yaml
中添加依赖:
dependencies:
geolocator: ^9.0.2
然后运行flutter pub get
。
- 在AndroidManifest.xml中加入权限:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
- 初始化Geolocator插件并请求位置:
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: LocationScreen(),
);
}
}
class LocationScreen extends StatefulWidget {
@override
_LocationScreenState createState() => _LocationScreenState();
}
class _LocationScreenState extends State<LocationScreen> {
String _locationMessage = "加载中...";
@override
void initState() {
super.initState();
_getLocation();
}
Future<void> _getLocation() async {
bool serviceEnabled;
LocationPermission permission;
serviceEnabled = await Geolocator.isLocationServiceEnabled();
if (!serviceEnabled) {
setState(() => _locationMessage = "位置服务已关闭");
return;
}
permission = await Geolocator.checkPermission();
if (permission == LocationPermission.denied) {
permission = await Geolocator.requestPermission();
if (permission == LocationPermission.denied) {
setState(() => _locationMessage = "权限被拒绝");
return;
}
}
if (permission == LocationPermission.deniedForever) {
setState(() => _locationMessage = "权限永久拒绝");
return;
}
Position position = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
setState(() => _locationMessage = "纬度: ${position.latitude}, 经度: ${position.longitude}");
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("获取位置")),
body: Center(child: Text(_locationMessage)),
);
}
}
这个代码实现了基本的位置获取功能。注意要处理好权限和位置服务的状态判断。
Flutter 获取地理位置教程
在Flutter中获取地理位置需要使用geolocator插件。以下是实现步骤:
1. 添加依赖
在pubspec.yaml
文件中添加geolocator依赖:
dependencies:
geolocator: ^10.0.0
然后运行flutter pub get
2. 配置权限
Android配置
在AndroidManifest.xml
中添加位置权限:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
iOS配置
在Info.plist
中添加:
<key>NSLocationWhenInUseUsageDescription</key>
<string>需要您的位置权限来提供定位服务</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>需要您的位置权限来提供定位服务</string>
3. 代码实现
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: LocationScreen(),
);
}
}
class LocationScreen extends StatefulWidget {
@override
_LocationScreenState createState() => _LocationScreenState();
}
class _LocationScreenState extends State<LocationScreen> {
Position? _currentPosition;
String _error = '';
Future<void> _getCurrentLocation() async {
try {
bool serviceEnabled = await Geolocator.isLocationServiceEnabled();
if (!serviceEnabled) {
setState(() {
_error = '位置服务未开启';
});
return;
}
LocationPermission permission = await Geolocator.checkPermission();
if (permission == LocationPermission.denied) {
permission = await Geolocator.requestPermission();
if (permission == LocationPermission.denied) {
setState(() {
_error = '位置权限被拒绝';
});
return;
}
}
if (permission == LocationPermission.deniedForever) {
setState(() {
_error = '位置权限被永久拒绝';
});
return;
}
Position position = await Geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.high,
);
setState(() {
_currentPosition = position;
_error = '';
});
} catch (e) {
setState(() {
_error = '获取位置失败: ${e.toString()}';
});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('获取位置')),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
if (_currentPosition != null)
Text(
"纬度: ${_currentPosition!.latitude}\n经度: ${_currentPosition!.longitude}",
textAlign: TextAlign.center,
),
if (_error.isNotEmpty) Text(_error),
ElevatedButton(
child: Text("获取位置"),
onPressed: _getCurrentLocation,
),
],
),
),
);
}
}
4. 功能说明
- 首先检查位置服务是否开启
- 检查并请求位置权限
- 获取当前位置坐标
- 处理可能出现的错误情况
你可以根据需要调整desiredAccuracy
参数来设置定位精度,可选值有:
- LocationAccuracy.lowest
- LocationAccuracy.low
- LocationAccuracy.medium
- LocationAccuracy.high
- LocationAccuracy.best