【问题标题】:How do I return the flotter geolocator position value? (programming language : dart)如何返回 flotter 地理定位器位置值? (编程语言:飞镖)
【发布时间】:2020-12-07 03:11:54
【问题描述】:

我正在使用颤振制作应用程序。

我正在尝试使用地理定位器库将位置值保存到变量中,但由于以下错误,我无法打印该值。

请看下面的代码,告诉我如何将返回位置值保存在变量中。谢谢。

/* Convert to location using Geolocator */
Future<Position> _getLocation() async {
    return Geolocator()
        .getCurrentPosition(desiredAccuracy: LocationAccuracy.low)
        .then((location) {
      return location;
    });
  }

/* run app */

  @override
  Widget build(BuildContext context) {
    _getUser();
    print(_getLocation());
    
    - omit below -
    
/*  =============================== */
/*  Output value when the app runs  */
/*  Instance of 'Future<Position>'  */
/*  =============================== */

【问题讨论】:

  • 欢迎来到 StackOverflow!您正在尝试打印承诺而不是位置。你试过print(await _getLocation());吗?

标签: flutter dart


【解决方案1】:
   Future<Position> _getLocation() async {
          return await Geolocator()
              .getCurrentPosition(desiredAccuracy: LocationAccuracy.low);
        }

Position userPosition = await _getLocation();
print(userPosition);

【讨论】:

  • 如果我将 await 插入到 Widget 构建类中,则会出现带有红色下划线的错误。
  • ERROR LOG : await 表达式只能在异步函数中使用。
  • 你不应该在你的小部件类中使用这些。在状态类中定义 userPosition 变量并在有状态小部件的 initState() 方法中调用 _getLocation()。每次重新构建小部件时都会触发小部件构建中的方法和值,这不是一个好方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-16
  • 2013-08-21
  • 1970-01-01
相关资源
最近更新 更多