Flutter Widget 之Location

582 阅读1分钟

你在哪? 如果你发现你的Flutter应用程序需要知道运行设备的地理位置,你就需要位置信息包了

Location包提供了位置可用于获取设备的当前地理位置以及侦听更改

import 'package:location/location.dart';

var location = new Location();

但是在获取位置权限之前需要确保已启用设备的位置服务访问位置权限

ezgif.com-gif-maker.gif

值得庆幸的是,Location提供了一些方法来执行此操作。首先,你必须勾选serviceEnabled来确保弃用位置服务。

如果未启用你可以使用requestService要求用户启用它

var serviceEnable = await location.serviceEnabled();
if (!_serviceEnabled) {
    serviceEnabled = await location.requestService();
    if (!_serviceEnabled) {
        return;
    }
}

接下来,你必须请求权限才能获取设备的位置,与上一步类似,你可以使用hasPermission检查当前权限并使用requestPermission请求访问权限

_permissionGranted = await location.hasPermission();
if (_permissionGranted == PermissionStatus.denied) {
    _permissionGranted = await location.requestPermission();
    if (_permissionGranted != PermissionStatus.granted) {
        return;
    }
}

你进入后,只需调用getLocation

var currentLocation = await location.getLocation();

Location数据对象包含许多有关设备位置的有用数据,包括维度和经度,高度,航向,和速度。

image.png

你可以使用此数据显示地图,计算距离等等

另外,你可以使用onLocationChanged监听设备位置的变化。这样一来,你就可以随时跟踪位置


location.onLocationChanged.listen(
    (LocationData currentLocation) {
        // ...
    }
);

有关更多详细信息,示例和有趣的用例,请至pub.dev查看Location包

原文翻译自视频:视频地址