Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import 'dart:async';
- import 'package:app/src/models/packet_model.dart';
- import 'package:firebase_auth/firebase_auth.dart';
- import 'package:location/location.dart';
- import 'package:http/http.dart' as http;
- class LocationService {
- static const period = Duration(seconds: 60); // 1 minute
- Location location = Location(); // initializing location package
- void initService() async {
- // initializing location service and checking permissions
- getLocationEnabled();
- getLocationPermission();
- startLocationService();
- }
- void getLocationEnabled() async {
- // checking if location is enabled on the device
- bool _serviceEnabled = await location.serviceEnabled();
- if (!_serviceEnabled) {
- _serviceEnabled =
- await location.requestService(); // if not, request location service
- if (!_serviceEnabled) {
- return; // if still not enabled, return
- }
- }
- }
- void getLocationPermission() async {
- var permissionGranted = await location
- .hasPermission(); // checking if location permission is granted
- if (permissionGranted == PermissionStatus.denied) {
- permissionGranted = await location
- .requestPermission(); // if not, request location permission
- if (permissionGranted != PermissionStatus.granted) {
- return; // if still not granted, return
- }
- }
- }
- Future<LocationData?> getLocation() async {
- var currentLocation =
- await location.getLocation(); // getting current location
- PacketModel packet = PacketModel(
- // creating packet model
- latitude: currentLocation.latitude,
- longitude: currentLocation.longitude,
- userId: FirebaseAuth
- .instance.currentUser!.uid, // getting current user id from firebase
- );
- final response = await http.post(
- // sending packet to server
- Uri.parse("http:8080/api/v1/recieve-packet"),
- body: packet.toJson());
- }
- void startLocationService() {
- // starting location service
- Timer.periodic(period, (timer) {
- getLocation(); // getting location every minute
- print("Runs after each 10 seconds"); // printing to console
- });
- }
- }
Add Comment
Please, Sign In to add comment