简体   繁体   English

Flutter - Geolocator 包没有多次调用 Geolocator.getCurrentPosition()

[英]Flutter - Geolocator package is not calling Geolocator.getCurrentPosition() more than once

As the title says, I'm not being able to call Geolocator.getCurrentPosition() more than once.正如标题所说,我不能多次调用 Geolocator.getCurrentPosition() 。 I have logged the issue with the package team, but I'm wondering if it's something I'm doing wrong.我已经向包装团队记录了这个问题,但我想知道这是否是我做错了。

  Future getLocation() async {
    var currentLocation;
    try {
      currentLocation = await Geolocator.getCurrentPosition(
        desiredAccuracy: LocationAccuracy.medium,
      );
    } catch (e) {
      currentLocation = null;
    }
    return currentLocation;
  }

  void getLocation1() async {
    var location = await getLocation();
    print(location);
    print("First");
  }

  void getLocation2() async {
    var location = await getLocation();
    print(location);
    print("Second");
  }

  @override
  void initState() {
    super.initState();
    getLocation1();
    getLocation2();
  }

The console prints "Second" but not "First".控制台打印“第二”而不是“第一”。 When I remove the getLocation2() call, the console prints "First".当我删除 getLocation2() 调用时,控制台会打印“First”。 They are not able to be called in the same frame, and I don't know why this changed.他们不能在同一个框架中被调用,我不知道为什么会改变。 Am I doing anything wrong?我做错什么了吗?

I am assuming you are experiencing this behavior on iOS or macOS.我假设您在 iOS 或 macOS 上遇到了这种行为。 The reason is that Apple doesn't allow multiple active calls to the location stream.原因是 Apple 不允许对位置流进行多次活动调用。 What happens is that the getLocation2 method closes the active request currently running by the getLocation1 call.发生的情况是getLocation2方法关闭了当前由getLocation1调用运行的活动请求。

The easiest way to workaround this, is to return the same Future if the first request has not been finished yet:解决此问题的最简单方法是,如果第一个请求尚未完成,则返回相同的Future

  late Future<Position> _positionFuture;

  Future<Position> getLocation() async {
    if (_positionFuture != null && !_positionFuture!.isCompleted) {
      return _positionFuture;
    }

    _positionFuture = Geolocator.getCurrentPosition(
        desiredAccuracy: LocationAccuracy.medium,
      );
    return _positionFuture;
  }

  void getLocation1() async {
    var location = await getLocation();
    print(location);
    print("First");
  }

  void getLocation2() async {
    var location = await getLocation();
    print(location);
    print("Second");
  }

  @override
  void initState() {
    super.initState();
    getLocation1();
    getLocation2();
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM