我有一个旧的 flutter 项目,我向它添加了 web 支持,现在,我试图在 flutter web 中获取我的位置,所以我添加了 location到我的页面。 这是我的代码:
@override
void initState() {
super.initState();
_getLocation();
}
Future _getLocation() async {
Location location = new Location();
var _permissionGranted = await location.hasPermission();
_serviceEnabled = await location.serviceEnabled();
if (_permissionGranted != PermissionStatus.granted || !_serviceEnabled) {
_permissionGranted = await location.requestPermission();
_serviceEnabled = await location.requestService();
} else {
print("-----> $_serviceEnabled");
setState(() {
_serviceEnabled = true;
_loading = false;
});
}
try {
final LocationData currentPosition = await location.getLocation();
setState(() {
longitude = currentPosition.longitude.toString();
latitude = currentPosition.latitude.toString();
print(
'${widget.url}?BranchName=&latitude=${latitude}&longitude=${longitude}');
_loading = false;
});
} on PlatformException catch (err) {
_loading = false;
print("-----> ${err.code}");
}
}
通过chrome获取位置权限后,
什么都没发生! 在 vsCode 控制台中,我收到了这个错误:
Error: [object GeolocationPositionError]
at Object.createErrorWithStack (http://localhost:43705/dart_sdk.js:4351:12)
at Object._rethrow (http://localhost:43705/dart_sdk.js:37962:16)
at async._AsyncCallbackEntry.new.callback (http://localhost:43705/dart_sdk.js:37956:13)
at Object._microtaskLoop (http://localhost:43705/dart_sdk.js:37788:13)
at _startMicrotaskLoop (http://localhost:43705/dart_sdk.js:37794:13)
at http://localhost:43705/dart_sdk.js:33303:9
**使用@JS('navigator.geolocation')
我也是try this , 但从未调用过 success
方法,而且什么也没有。
最佳答案
现在(包括网络在内的所有平台),2021 年 6 月,使用 Location 包。
final Location location = new Location();
_locationData = await location.getLocation();
print(_locationData.latitude);
在此处查看完整详细信息: pub.dev/packages/location
关于flutter-web:通过 Location 插件在网络上获取位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64411270/