从Future获取位置时出错[VERBOSE-2:ui_dart_state.cc(148)]未处理的异常:无效的参数

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

我正在尝试获取用户的经度和纬度坐标,但是我无法从Future访问这些值。

目前,我正在使用Geolocator包来获取Future,但在检索值时遇到错误。

为了获得位置,这就是我正在做的事情:

Future<Position> locateUser() async {
  return Geolocator()
      .getCurrentPosition(desiredAccuracy: LocationAccuracy.high)
      .then((location) {
    if (location != null) {
      print("Location: ${location.latitude},${location.longitude}");
    }
    return location;
  });
}

要在构建Widget函数中检索这些坐标,我这样做:

bool firstTime = true;
String latitude;
String longitude;

  @override
  Widget build(BuildContext context) {
    if(firstTime == true) {
      locateUser().then((result) {
        setState(() {
          latitude = result.latitude.toString();
          longitude = result.longitude.toString();
        });
      });
      fetchPost(latitude, longitude);
      firstTime = false;
    }

我得到的错误是这样的:

[VERBOSE-2:ui_dart_state.cc(148)] Unhandled Exception: Invalid argument(s)

我希望能够将那些协调的变量存储起来并将它们传递给我拥有的其他函数。我对Flutter很新,所以任何帮助都将不胜感激!

dart flutter geolocation
1个回答
0
投票

您正在使用async方法,因此您可以使用await关键字来获取响应:

改变这个

            Future<Position> locateUser() async {
              return Geolocator()
                  .getCurrentPosition(desiredAccuracy: LocationAccuracy.high)
                  .then((location) {
                if (location != null) {
                  print("Location: ${location.latitude},${location.longitude}");
                }
                return location;
              });
            }

对此:

            Future<Position> locateUser() async {
              final location = await Geolocator().getCurrentPosition(desiredAccuracy: LocationAccuracy.high);

              if (location != null) {
                  print("Location: ${location.latitude},${location.longitude}");
               }

              return location;
            }

在回调中调用fetchPost(latitude, longitude)并从构建方法中删除调用并继续使用initState方法,或者可以使用FutureBuilder。

      @override
      void initState() {
        locateUser().then((result) {
            setState(() {
              latitude = result.latitude.toString();
              longitude = result.longitude.toString();
              fetchPost(latitude, longitude);
            });

          });
        super.initState();
      }
© www.soinside.com 2019 - 2024. All rights reserved.