import 'package:location/location.dart';
class LocationService {
UserLocation _currentLocation;
var location = Location();
//One off location
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.toString()}');
}
return _currentLocation;
}
//Stream that emits all user location updates to you
StreamController<UserLocation> _locationController =
StreamController<UserLocation>();
Stream<UserLocation> get locationStream => _locationController.stream;
LocationService() {
// Request permission to use location
location.requestPermission().then((granted) {
if (granted) {
// If granted listen to the onLocationChanged stream and emit over our controller
location.onLocationChanged().listen((locationData) {
if (locationData != null) {
_locationController.add(UserLocation(
latitude: locationData.latitude,
longitude: locationData.longitude,
));
}
});
}
});
}
}
用户位置模型:
class UserLocation {
final double latitude;
final double longitude;
final double heading;
UserLocation({required this.heading, required this.latitude, required this.longitude});
}
1条答案
按热度按时间mnemlml81#
在你的应用中创建服务。你可以使用以下代码提供位置服务。
用户位置模型:
然后在你的页面/视图初始化函数中,启动一个计时器,并将位置更新为你的位置API或Firebase。
如果不使用计时器,请记住将其丢弃。
这将在应用程序运行或后台运行时每60秒更新一次位置。在应用程序终止时更新位置有点复杂,但有一个软件包会每15秒唤醒一次应用程序。您可以通过以下链接查看如何实现此功能的文档:
https://pub.dev/packages/background_fetch