首页 > 解决方案 > 在 Flutter 中捕获前台位置

问题描述

有什么官方方法可以在 Flutter 中捕捉前景的位置吗?或者请给我您的反馈,我的方式是否可以。(安卓和IOS都可以)

如果用户单击开始按钮,行程将开始。如果用户单击结束按钮,行程将结束。

目前,我将当前地理点存储到数组

 List<GeoPoint> tripGeoPoint = [];

 @override
  Widget build(BuildContext context) {
    //Stream location data using this plugin -> `location`
    UserLocation userLocation = Provider.of<UserLocation>(context);

    if (startTrip) {
      tripGeoPoint.add(GeoPoint(userLocation.latitude, userLocation.longitude));
    }

我目前正在使用这种方式来捕捉前景的位置。(我认为这不是在前台捕获位置的正确解决方案)

  Timer _timer;

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    switch (state) {
      case AppLifecycleState.resumed:
        {
          if (_timer != null) _timer.cancel();
          print("app in resumed");
          break;
        }
      case AppLifecycleState.inactive://foreground
        {
          print("app in inactive");
          const oneSec = const Duration(seconds: 3);
          _timer = Timer.periodic(oneSec, (Timer t) async {
            UserLocation _loc = await getLocation();
            GeoPoint geoPoint = GeoPoint(_loc.latitude, _loc.longitude);
            tripGeoPoint.add(geoPoint);
          });
          break;
        }
      case AppLifecycleState.paused:
        break;
      case AppLifecycleState.detached:
        break;
    }
  }

用于在前台捕获位置的顶级功能

var location = Location();
UserLocation _currentLocation;

Future<UserLocation> getLocation() async {
  try {
    var userLocation = await location.getLocation();
    _currentLocation = UserLocation(latitude: userLocation.latitude, longitude: userLocation.longitude);
  } on Exception catch (e) {
    print('Could not get location: $e');
  }
  return _currentLocation;
}

标签: androidiosflutterdart

解决方案


我找到了两个插件来实现这一点。

(付费) 目前,我正在将此插件用于生产项目flutter_background_geolocation

替代(免费) background_locator


推荐阅读