【问题标题】:Latitude and Longitude is getting null in Flutter (Get Current Location)Flutter 中的纬度和经度为空(获取当前位置)
【发布时间】:2021-11-14 14:16:30
【问题描述】:

我正在使用这个插件flutter_geofence 来获取当前位置的纬度和经度。下面是示例 dart 代码,我面临的问题是在 Geofence 主体内部,我可以获得纬度和经度,但是当我尝试访问外部时,它会变为空。

return Scaffold(
          body: Container(
            child: GestureDetector(
                onTap: () {
                  var latitude;
                  var longitude;
                  Geofence.initialize();
                  Geofence.requestPermissions();
                  Geofence.getCurrentLocation().then((cd) {
                    latitude = cd!.latitude;
                    longitude = cd.longitude;
                  });
                  print(latitude); // getting null
                  print(longitude); // getting null
                },
                child: Center(child: Text('Test'))),
          ),
        );

DataService.class

class DataService {
Future<List<RecommendedForYouData>?> makeRequestRecommendedForYou(
      BuildContext context) async {
var latitude;
var longitude;
Geofence.initialize();
                  Geofence.requestPermissions();
                  Geofence.getCurrentLocation().then((cd) {
                    latitude = cd!.latitude;
                    longitude = cd.longitude;
                  });
                  print(latitude); // getting null
                  print(longitude); // getting null
}
}

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    这个问题发生是因为你的变量在函数之外 (Geofence.getCurrentLocation().then ...),如果你把这个变量放在 {} 中,你可能会得到与 null 不同的值,但我建议创建一个新函数在构建方法之外。

    1. 如果您使用有状态小部件:
    • 在类的顶部声明变量。
    • 使用 initState 并在内部调用您的方法(Geofence.initialize()、Geofence.requestPermissions()、Geofence.getCurrentLocation())
    • 您可以在 initState 之外创建一个特定函数以在您的构建方法内部调用。
    • 在您的特定函数中,您需要调用 setState 函数来重建您的 UI。

    我建议您使用 bloc 或 provider 之类的状态管理来代替 setState。

    【讨论】:

    • 如果它不是 StateFul 或 Stateless Widget,它只是一个简单的类,那么如何做到这一点?
    • 我还添加了一些类中的代码
    • 您的 DataServices 类可以扩展“更改通知程序”,然后您可以将此类注入您的小部件树的顶部,以在您的小部件中使用她的函数或变量。我建议您使用提供者状态管理(或其他),但是您可以在小部件树的顶部注入此类,然后实例化此 DataService 类并使用她的变量。
    猜你喜欢
    • 2021-09-29
    • 1970-01-01
    • 2012-07-08
    • 1970-01-01
    • 2011-08-31
    • 1970-01-01
    • 2017-05-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多