权限与定位是高频又高风险的能力:权限拒绝、系统限制、异常场景多。本文使用 permission_handler + geolocator 给出一套可复用的完整实践。
0. 依赖与平台配置
dependencies:
permission_handler: ^10.2.0
geolocator: ^10.1.0
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>
1. 权限检查与申请
Future<bool> ensureLocationPermission() async {
var status = await Permission.location.status;
if (status.isDenied) {
status = await Permission.location.request();
}
return status.isGranted;
}
2. 异常兜底与引导
Future<void> checkAndNavigate() async {
final granted = await ensureLocationPermission();
if (!granted) {
openAppSettings();
}
}
3. 获取定位
Future<Position> getCurrentLocation() async {
final serviceEnabled = await Geolocator.isLocationServiceEnabled();
if (!serviceEnabled) {
throw Exception('定位服务未开启');
}
return Geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.high,
);
}
4. 组合调用
Future<Position?> safeLocation() async {
final granted = await ensureLocationPermission();
if (!granted) return null;
try {
return await getCurrentLocation();
} catch (_) {
return null;
}
}
5. 实践清单
- 先检查再申请
- 引导用户到系统设置
- 捕获异常兜底
- 业务层不直接抛异常
总结
权限与定位必须把“拒绝与异常”当成常态处理,只有这样体验才稳定。