背景中的Flutter Live位置

yeotifhr  于 2023-10-22  发布在  Flutter
关注(0)|答案(1)|浏览(147)

我想实现我们的内部Flutter应用程序之一的实时位置跟踪。这是一个内部团队应用程序,在那里我们应该能够跟踪和推动我们的团队成员的位置,我们的后端服务器在30秒的频率。即使应用程序进入后台,这也应该可用。需要免费的解决方案。
提前感谢您
我尝试了一些flutter插件,如location,background_location,geolocation,但它没有工作

zfycwa2u

zfycwa2u1#

使用此软件包location: ^5.0.3并尝试使用此代码:

import 'package:location/location.dart';

Future<LocationData?> getCurrentLocation() async {
  Location location = Location();
  bool serviceEnabled;
  PermissionStatus permissionStatus;

  try {
    serviceEnabled = await location.serviceEnabled();
    if (!serviceEnabled) {
      serviceEnabled = await location.requestService();
      if (!serviceEnabled) {
        // Service not enabled, handle accordingly
        return null;
      }
    }

    permissionStatus = await location.hasPermission();
    if (permissionStatus == PermissionStatus.denied) {
      permissionStatus = await location.requestPermission();
      if (permissionStatus != PermissionStatus.granted) {
        // Permission not granted, handle accordingly
        return null;
      }
    }
    
    return await location.getLocation();
  } catch (e) {
    logE(message: 'Error getting current location: $e');
    return null;
  }
}

如何拨打:

getCurrentLocation().then((location) {
  if (location != null) {
    // Use location here
    print(location.latitude ?? 0);
    print(location.longitude ?? 0);
  } else {
    print('Getting error on fetch');
  }
}).onError((error, stackTrace) {
  print('onError $error');
});
  • 确保已启用设备位置。*

更新:

使用此包管理应用程序时,它在后台

Package 名称:move_to_backgroundPackage Link

相关问题