首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从Future [VERBOSE-2:ui_dart_state.cc(148)]获取位置时出错:未处理的异常:参数无效

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

Stack Overflow用户
提问于 2019-04-16 03:40:57
回答 1查看 2.5K关注 0票数 0

我正在尝试获取用户的经度和纬度坐标,但在从Future访问这些值时遇到了问题。

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

为了获取位置,我正在做以下操作:

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

为了在build Widget函数中检索这些坐标,我执行以下操作:

代码语言:javascript
复制
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;
    }

我得到的错误是:

代码语言:javascript
复制
[VERBOSE-2:ui_dart_state.cc(148)] Unhandled Exception: Invalid argument(s)

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

EN

回答 1

Stack Overflow用户

发布于 2019-04-16 03:45:03

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

改变这一点

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

要这样做:

代码语言:javascript
复制
            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),从build方法中移除你的调用,转移到initState方法上,或者你也可以使用FutureBuilder。

代码语言:javascript
复制
      @override
      void initState() {
        locateUser().then((result) {
            setState(() {
              latitude = result.latitude.toString();
              longitude = result.longitude.toString();
              fetchPost(latitude, longitude);
            });

          });
        super.initState();
      }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55696199

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档