如何在Flutter中使用geolocator包打印当前位置至控制台,调用无响应如何处理
核心问题原因
- 现有代码直接调用
getCurrentPosition发起定位请求,完全省略前置校验步骤:当系统定位服务未开启、应用未获得定位权限时,请求会被系统拦截,抛出的异常因为没有被try-catch捕获,会被Flutter静默吞掉,根本执行不到打印位置信息的逻辑 - 缺失原生平台权限配置:仅在Dart层编写定位逻辑,没有在Android、iOS的原生配置文件中声明定位权限,系统会直接拦截所有定位请求,触发按钮时完全无响应
- 代码中使用的
RaisedButton组件已在Flutter 3.10+版本正式废弃,部分高版本运行环境下可能存在组件交互异常的问题
修复后的可运行代码
import 'package:flutter/material.dart'; import 'package:geolocator/geolocator.dart'; class LoadingScreen extends StatefulWidget { @override _LoadingScreenState createState() => _LoadingScreenState(); } class _LoadingScreenState extends State<LoadingScreen> { void getLocation() async { try { // 校验系统定位服务是否开启 bool serviceEnabled = await Geolocator.isLocationServiceEnabled(); if (!serviceEnabled) { debugPrint('提示:系统定位服务未开启,请先到系统设置打开定位'); return; } // 校验应用定位权限状态 LocationPermission permission = await Geolocator.checkPermission(); if (permission == LocationPermission.denied) { // 权限被拒绝时主动发起权限申请 permission = await Geolocator.requestPermission(); if (permission == LocationPermission.denied) { debugPrint('提示:定位权限被拒绝,无法获取位置信息'); return; } } // 权限被永久拒绝的分支处理 if (permission == LocationPermission.deniedForever) { debugPrint('提示:定位权限被永久拒绝,需要手动到应用设置开启定位权限'); return; } // 所有校验通过后发起定位请求 Position position = await Geolocator.getCurrentPosition( desiredAccuracy: LocationAccuracy.low, ); debugPrint('当前获取到的位置信息:$position'); } catch (e) { // 捕获定位过程中的所有异常,避免逻辑静默中断 debugPrint('定位请求发生异常:$e'); } } @override Widget build(BuildContext context) { return Scaffold( body: Center( // 替换已废弃的RaisedButton为官方推荐的ElevatedButton child: ElevatedButton( onPressed: () { getLocation(); }, child: const Text('Get Location'), ), ), ); } }
必须补全的平台配置
- 安卓端:编辑
android/app/src/main/AndroidManifest.xml,在<manifest>根标签下添加定位权限声明:<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> - iOS端:编辑
ios/Runner/Info.plist,在<dict>根标签内添加定位权限的用户描述,否则系统不会弹出权限申请弹窗:<key>NSLocationWhenInUseUsageDescription</key> <string>需要获取您的位置信息实现定位功能</string>
内容的提问来源于stack exchange,提问作者suyog shelar
相关产品推荐
相关产品推荐

