使用 Flutter 中的 Location 包获取用户位置
我正在尝试在 Flutter 中创建一个移动应用程序。
当我按下按钮时,我需要获取用户位置。在互联网上阅读,我发现了一些有用的示例,并且我也按照一些教程编写了一些代码行。
Future<void> getLocation() async {
var _serviceEnabled = await location.serviceEnabled();
if (!_serviceEnabled) {
_serviceEnabled = await location.requestService();
if (!_serviceEnabled) {
return;
}
}
var _permissionGranted = await location.hasPermission();
if (_permissionGranted == PermissionStatus.denied) {
_permissionGranted = await location.requestPermission();
if (_permissionGranted != PermissionStatus.granted) {
return;
}
}
var currentLocation = await location.getLocation();
setState(() {
current = currentLocation;
string = currentLocation.latitude!.toString() +
' ' +
currentLocation.longitude!.toString();
});
通过这段代码,
我应该能够使用用户位置的纬度和经度更新字符串的文本。
它无法正常工作。有人可以帮助我吗?
我正在使用 Android Studio 通过模拟器启动应用程序。
I'm trying to create a mobile app in Flutter.
I need to get the user location when I press a button. Reading on the Internet, I found some useful examples and I wrote some lines of code following some tutorials too.
Future<void> getLocation() async {
var _serviceEnabled = await location.serviceEnabled();
if (!_serviceEnabled) {
_serviceEnabled = await location.requestService();
if (!_serviceEnabled) {
return;
}
}
var _permissionGranted = await location.hasPermission();
if (_permissionGranted == PermissionStatus.denied) {
_permissionGranted = await location.requestPermission();
if (_permissionGranted != PermissionStatus.granted) {
return;
}
}
var currentLocation = await location.getLocation();
setState(() {
current = currentLocation;
string = currentLocation.latitude!.toString() +
' ' +
currentLocation.longitude!.toString();
});
}
With this code I should be able to update the text of a string with the latitude and longitude of the user position.
It doesn't work properly. Can anybody help me?
I'm using Android Studio for launching the app with the emulator.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
[已解决]
问题出在模拟器上。
在模拟器中启动应用程序我无法获取位置。我尝试在物理设备(Android)上启动该应用程序,它成功了。问题可能是模拟器已被弃用。
[RESOLVED]
The problem was the emulator.
Launching the app in the emulator I wasn't able to get the location. I tried to launch the app on a physical device (with Android) and it worked. Probably the problem was that the emulator's was deprecated.