google-maps - 无法在 Flutter 应用程序中加载当前位置
问题描述
我正在使用地理定位器插件并获取当前的纬度和经度,但我无法在我的 Flutter 应用程序的 initstate 中加载它。它显示渲染错误。
void initState() {
// TODO: implement initState
super.initState();
getCurrentLocation();
}
void getCurrentLocation() async {
var answer = await Geolocator().getCurrentPosition();
setState(() {
latitude = answer.latitude;
longitude = answer.longitude;
});
}
几毫秒后地图已更新为当前位置,但显示了这些错误。I/flutter (14143):══╡小部件库发现异常╞═════════════════════════════════════════════ ═════════════════════════
I/flutter (14143):在构建 HomePage(dirty, state: _HomePageState#d55de) 时抛出了以下断言:
I/flutter (14143): 'package:google_maps_flutter/src/location.dart': 断言失败: line 17 pos 16: 'latitude !=
I/flutter (14143): null': 不正确。
我/颤振(14143):
I/flutter (14143):要么断言表明框架本身有错误,要么我们应该提供大量
I/flutter (14143):此错误消息中的更多信息可帮助您确定和修复根本原因。
I/flutter (14143):无论哪种情况,请通过在 GitHub 上提交错误来报告此断言:
解决方案
我尝试了很多方法,直到我找到了这种方法,这要感谢一个在另一个颤振 facebook 小组上提供帮助的好心人。确保在您的 pubspec.yaml 中将位置更新为最新版本
dependencies: location: ^2.3.5 然后改成如下代码:
LocationData _currentLocation;
StreamSubscription<LocationData> _locationSubscription;
var _locationService = new Location();
String error;
void initState() {
super.initState();
initPlatformState();
_locationSubscription = _locationService
.onLocationChanged()
.listen((LocationData currentLocation) async {
setState(() {
_currentLocation = currentLocation;
});
});
}
void initPlatformState() async {
try {
_currentLocation = await _locationService.getLocation();
} on PlatformException catch (e) {
if (e.code == 'PERMISSION_DENIED') {
error = 'Permission denied';
}else if(e.code == "PERMISSION_DENIED_NEVER_ASK"){
error = 'Permission denied';
}
_currentLocation = null;
}
Run code snippetReturn to post
您可以访问经度和纬度为
_currentLocation.longitude 和 _currentLocation.latitude
这些将返回双精度值。此外,还有更多可用的选项https://pub.dev/packages/location#-readme-tab-
推荐阅读
- java - restFb 中的长轮询我如何实现这个
- javascript - 我可以在 load() 函数加载的元素上添加/删除类吗?
- jenkins - 在 Jenkins 共享库中使用外部 jar 的问题
- php - Laravel - 无法为名为“edge_50mm”的字段创建访问器
- ssl - 使用客户端证书验证保护特定的 nginx 入口位置
- python - 使用 Serpy 进行动态字段序列化
- javascript - Chrome - alert() 的 Javascript 执行顺序问题
- scala - Spark scala:将键值对中的数值更改为长/整数以加入两个地图
- c# - HTMLAgilityPack C# 获取所有节点和子节点
- r - 将函数应用于矩阵的每一行而不使用 R 中的 lapply 函数