如何使用flutter在Android设备上获取当前位置。我试过了Location和GeoLocator插件GeoLocator 3.0.0在debuging上显示了这个错误:
Launching lib\main.dart on Android SDK built for x86 in debug mode...
FAILURE:构建因异常而失败。
位置2.0.0也会在调试时抛出错误。还有另一个名为geoLocation的插件,但它与dart 2.0不兼容。在这种情况下,我怎样才能获得位置(经度和纬度)[一次]?任何帮助将受到高度赞赏。
现在你可能已经找到了解决方案,但我仍然可以添加这个,以便其他人可以获得帮助
使用geolocator获取当前位置
在pubsec.yaml中
geolocator: '^2.0.1'
在你的飞镖文件中
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
void main() => runApp(MapScreen());
class MapScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: "Map",
home: MapActivity(),
);
}
}
class MapActivity extends StatefulWidget {
@override
_MapActivityState createState() => _MapActivityState();
}
class _MapActivityState extends State<MapActivity> {
LatLng _center ;
Position currentLocation;
@override
void initState() {
// TODO: implement initState
super.initState();
getUserLocation();
}
Future<Position> locateUser() async {
return Geolocator()
.getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
}
getUserLocation() async {
currentLocation = await locateUser();
setState(() {
_center = LatLng(currentLocation.latitude, currentLocation.longitude);
});
print('center $_center');
}
}
希望这可以帮助
我安装的geoLocator插件使用Android x jetpack库,而我的项目使用支持库,因此这个冲突导致了问题,当我更新我的项目以使用Android x库时问题得到了解决。
按照以下步骤在IOS和Android中获取位置。
geolocator: ^4.0.3
下面的依赖项:tagimport 'package:geolocator/geolocator.dart';
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission
android:name="android.permission.ACCESS_COARSE_LOCATION" />
<dict>
下的info.plist文件中添加以下行
<key>NSLocationWhenInUseUsageDescription</key>
<string>This app needs access to location when open.</string>
void getLocation() async {
Position position = await Geolocator()
.getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
print(position);
}
干杯!