import 'package:geolocator/geolocator.dart'; /// Kiểm tra xem dịch vụ vị trí có được bật không Future isLocationServiceEnabled() async { bool serviceEnabled = await Geolocator.isLocationServiceEnabled(); if (!serviceEnabled) { print('Vui lòng bật dịch vụ vị trí'); return false; } return true; } /// Kiểm tra và yêu cầu quyền truy cập vị trí Future checkAndRequestPermission() async { LocationPermission permission = await Geolocator.checkPermission(); if (permission == LocationPermission.denied) { permission = await Geolocator.requestPermission(); if (permission == LocationPermission.denied) { print('Quyền truy cập vị trí bị từ chối'); return permission; } } if (permission == LocationPermission.deniedForever) { print('Quyền truy cập vị trí bị từ chối vĩnh viễn. Vui lòng cấp quyền trong cài đặt.'); return permission; } return permission; } /// Lấy vị trí hiện tại của người dùng Future getCurrentPosition() async { try { Position position = await Geolocator.getCurrentPosition( desiredAccuracy: LocationAccuracy.high, ); print('Vị trí hiện tại: ${position.latitude}, ${position.longitude}'); return position; } catch (e) { print('Lỗi khi lấy vị trí: $e'); return null; } } /// Hàm chính để xử lý toàn bộ quy trình yêu cầu vị trí Future requestLocationPermission() async { // Bước 1: Kiểm tra dịch vụ vị trí bool isServiceEnabled = await isLocationServiceEnabled(); if (!isServiceEnabled) { return; } // Bước 2: Kiểm tra và yêu cầu quyền LocationPermission permission = await checkAndRequestPermission(); // Bước 3: Nếu quyền được cấp, lấy vị trí if (permission == LocationPermission.whileInUse || permission == LocationPermission.always) { await getCurrentPosition(); } }