我正在使用地理定位器插件并获取当前的纬度和经度,但我无法在 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': 断言失败: 第 17 行 pos 16: '纬度 !=
I/flutter (14143): null': 不正确。
我/颤振(14143):
I/flutter (14143):要么该断言表明框架本身存在错误,要么我们应该提供实质内容
I/flutter (14143):此错误消息中的更多信息可帮助您确定并修复根本原因。
I/flutter (14143):无论哪种情况,请通过在 GitHub 上提交错误来报告此断言:
我尝试了很多方法,直到我找到了这种方法,这要感谢一位好心人在另一个 flutter facebook 群组上提供的帮助。确保在 pubspec.yaml 中将位置更新为最新版本
依赖项:
地点:^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-
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)