FahimHoque

location_service.dart

Dec 7th, 2021 (edited)
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.18 KB | None | 0 0
  1. import 'dart:async';
  2. import 'package:app/src/models/packet_model.dart';
  3. import 'package:firebase_auth/firebase_auth.dart';
  4. import 'package:location/location.dart';
  5. import 'package:http/http.dart' as http;
  6.  
  7. class LocationService {
  8. static const period = Duration(seconds: 60); // 1 minute
  9. Location location = Location(); // initializing location package
  10.  
  11. void initService() async {
  12. // initializing location service and checking permissions
  13. getLocationEnabled();
  14. getLocationPermission();
  15. startLocationService();
  16. }
  17.  
  18. void getLocationEnabled() async {
  19. // checking if location is enabled on the device
  20. bool _serviceEnabled = await location.serviceEnabled();
  21. if (!_serviceEnabled) {
  22. _serviceEnabled =
  23. await location.requestService(); // if not, request location service
  24. if (!_serviceEnabled) {
  25. return; // if still not enabled, return
  26. }
  27. }
  28. }
  29.  
  30. void getLocationPermission() async {
  31. var permissionGranted = await location
  32. .hasPermission(); // checking if location permission is granted
  33. if (permissionGranted == PermissionStatus.denied) {
  34. permissionGranted = await location
  35. .requestPermission(); // if not, request location permission
  36. if (permissionGranted != PermissionStatus.granted) {
  37. return; // if still not granted, return
  38. }
  39. }
  40. }
  41.  
  42. Future<LocationData?> getLocation() async {
  43. var currentLocation =
  44. await location.getLocation(); // getting current location
  45. PacketModel packet = PacketModel(
  46. // creating packet model
  47. latitude: currentLocation.latitude,
  48. longitude: currentLocation.longitude,
  49. userId: FirebaseAuth
  50. .instance.currentUser!.uid, // getting current user id from firebase
  51. );
  52. final response = await http.post(
  53. // sending packet to server
  54. Uri.parse("http:8080/api/v1/recieve-packet"),
  55. body: packet.toJson());
  56. }
  57.  
  58. void startLocationService() {
  59. // starting location service
  60. Timer.periodic(period, (timer) {
  61. getLocation(); // getting location every minute
  62. print("Runs after each 10 seconds"); // printing to console
  63. });
  64. }
  65. }
  66.  
Add Comment
Please, Sign In to add comment