使用 Flutter 中的 Location 包获取用户位置

发布于 2025-01-11 00:50:54 字数 955 浏览 0 评论 0原文

我正在尝试在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

无声静候 2025-01-18 00:50:54

[已解决]
问题出在模拟器上。

在模拟器中启动应用程序我无法获取位置。我尝试在物理设备(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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文