它将打开设置。所以用户可以启用它。据我所知,这是最佳实践。
安装插件:
https://pub.dartlang.org/packages/android_intent#-installing-tab-
导入你的飞镖:
import 'package:android_intent/android_intent.dart';
Run Code Online (Sandbox Code Playgroud)
添加方法:
void openLocationSetting() async {
final AndroidIntent intent = new AndroidIntent(
action: 'android.settings.LOCATION_SOURCE_SETTINGS',
);
await intent.launch();
}
Run Code Online (Sandbox Code Playgroud)
调用完成...
小智 7
我将使用从该链接学到的东西来指导您。
添加此依赖项pubspec.yaml
dependencies:
location: ^3.0.0
Run Code Online (Sandbox Code Playgroud)
现在,将以下包导入到您的.dart文件中
import 'package:location/location.dart';
Run Code Online (Sandbox Code Playgroud)
现在在一个函数中,要使用弹出框询问用户的位置,您可以执行以下操作:
Location location = new Location();
bool _serviceEnabled;
LocationData _locationData;
Run Code Online (Sandbox Code Playgroud)
以上是我们将在以下代码中使用的声明 -
_serviceEnabled = await location.serviceEnabled();
if (!_serviceEnabled) {
_serviceEnabled = await location.requestService();
if (!_serviceEnabled) {
debugPrint('Location Denied once');
}
}
Run Code Online (Sandbox Code Playgroud)
现在,您可以根据您的要求使用上面的代码片段,通过弹出窗口进行位置请求调用,次数不限。
如果用户的位置已被授予,您可以使用以下行来存储和使用位置数据。
_locationData = await location.getLocation();
Run Code Online (Sandbox Code Playgroud)
如果未授予位置,则上述行将导致程序失败,因此请确保仅当用户允许从弹出窗口访问位置时才使用上述行。
希望这可以帮助。干杯!
首先在 pubspec.yaml 中添加此依赖项:
location: ^1.4.0
Run Code Online (Sandbox Code Playgroud)
然后,使用此函数检索设备的当前位置:
import 'package:location/location.dart';
fetchCurrentLocation() async {
print("STARTING LOCATION SERVICE");
var location = Location();
location.changeSettings(accuracy: LocationAccuracy.POWERSAVE,interval: 1000,distanceFilter: 500);
if (!await location.hasPermission()) {
await location.requestPermission();
}
try {
await location.onLocationChanged().listen((LocationData currentLocation) {
print(currentLocation.latitude);
print(currentLocation.longitude);
latitude = currentLocation.latitude;
longitude = currentLocation.longitude;
});
} on PlatformException {
location = null;
}
Run Code Online (Sandbox Code Playgroud)
}
| 归档时间: |
|
| 查看次数: |
3485 次 |
| 最近记录: |