Flutter 应用程序无法使用地理定位器和地理编码自动更新位置

问题描述 投票:0回答:1

我正在 flutter 和 android 中构建一个应用程序,几天后我遇到了一个问题,它不会自动更新位置。

这是代码:

geolocator
    // If permission is granted, retrieve the current position
    if (serviceEnabled) {

      try {
       
        LocationSettings locationSettings = const LocationSettings(
          accuracy: LocationAccuracy.high,
          distanceFilter: 10000,  
        );

        GeolocatorPlatform.instance.getPositionStream(locationSettings: locationSettings).listen((Position position) async {

        final String currentTimeZone = await FlutterTimezone.getLocalTimezone();
        prayerTimeAPI(position.latitude, position.longitude, currentTimeZone);
        getAddress(position.latitude, position.longitude);
        update();
      }); }
      catch (e) {
        await prefs.setBool("isLocationDenied", true);
        bool? storedFontSize = prefs.getBool("isLocationDenied");
        if (storedFontSize != null) {
          isLocationDenied.value = storedFontSize;
        }

geocoding
// Get Address Function====>
  getAddress(double lat, double long) async {
    try {
      List<Placemark> addressList = await placemarkFromCoordinates(lat, long);

      final callAddress = addressList.first;
      currentAddress.value = callAddress.locality!;
      update();
    } catch (e) {
      print("Location not found");
    }
  }

我希望位置在 ui 应用程序中自动更新。 如果需要的话我可以提供更多信息。谢谢

flutter geocoding geolocator
1个回答
0
投票

数据部分,使用Geolocator: 首先,确保获得许可:

var permission = await Geolocator.checkPermission();
if (permission != LocationPermission.always && permission != LocationPermission.whileInUse) {
permission = await Geolocator.requestPermission();

如果需要,还要检查准确性。

第二:你需要在收听之前提出一个请求

await Geolocator.getCurrentPosition();

获取蒸汽:

Stream<Position> positionStream = Geolocator.getPositionStream(
locationSettings: LocationSettings(timeLimit: Duration(seconds: 5)));

处理事件:

positionStream.listen((position) {...

如果没有帮助,请添加记录器,并确保问题出在数据部分,而不是用户界面。如果您有 ui 更新问题,请编写您的 ui 实现。

© www.soinside.com 2019 - 2024. All rights reserved.