code added to get the location for gms hms and iphone. fallback added if the last known location is null.

pull/48/head
taha.alam 1 month ago
parent 05500e4cd1
commit 3fdd17ccaa

@ -133,5 +133,10 @@ class AppState {
_userRegistrationPayload = value; _userRegistrationPayload = value;
} }
///this will be called if there is any problem in getting the user location
void resetLocation(){
userLong = 0.0;
userLong = 0.0;
}
} }

@ -158,7 +158,8 @@ class AppDependencies {
bookAppointmentsRepo: getIt(), bookAppointmentsRepo: getIt(),
errorHandlerService: getIt(), errorHandlerService: getIt(),
navigationService: getIt(), navigationService: getIt(),
myAppointmentsViewModel: getIt() myAppointmentsViewModel: getIt(),
locationUtils: getIt()
), ),
); );

@ -1,12 +1,23 @@
import 'dart:io'; import 'dart:io';
import 'dart:ui';
import 'package:geolocator/geolocator.dart'; import 'package:geolocator/geolocator.dart';
import 'package:gms_check/gms_check.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart'; import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:hmg_patient_app_new/core/app_state.dart'; import 'package:hmg_patient_app_new/core/app_state.dart';
import 'package:hmg_patient_app_new/core/cache_consts.dart'; import 'package:hmg_patient_app_new/core/cache_consts.dart';
import 'package:hmg_patient_app_new/core/utils/utils.dart'; import 'package:hmg_patient_app_new/core/utils/utils.dart';
import 'package:hmg_patient_app_new/services/navigation_service.dart'; import 'package:hmg_patient_app_new/services/navigation_service.dart';
import 'package:permission_handler/permission_handler.dart'; import 'package:huawei_location/huawei_location.dart' as HmsLocation
show
FusedLocationProviderClient,
Location,
LocationSettingsRequest,
LocationRequest;
import 'package:location/location.dart'
show Location, PermissionStatus, LocationData;
import 'package:permission_handler/permission_handler.dart'
show Permission, PermissionListActions, PermissionStatusGetters;
class LocationUtils { class LocationUtils {
NavigationService navigationService; NavigationService navigationService;
@ -16,6 +27,7 @@ class LocationUtils {
bool isShowLocationTimeoutDialog; bool isShowLocationTimeoutDialog;
bool isHuawei; bool isHuawei;
final GeolocatorPlatform _geolocatorPlatform = GeolocatorPlatform.instance; final GeolocatorPlatform _geolocatorPlatform = GeolocatorPlatform.instance;
Future<bool?>? isGMSDevice;
LocationUtils({ LocationUtils({
required this.isShowConfirmDialog, required this.isShowConfirmDialog,
@ -23,49 +35,62 @@ class LocationUtils {
required this.appState, required this.appState,
this.isHuawei = false, this.isHuawei = false,
this.isShowLocationTimeoutDialog = true, this.isShowLocationTimeoutDialog = true,
}); }) {
isGMSDevice = GmsCheck().checkGmsAvailability();
void getCurrentLocation({Function(LatLng)? callBack}) async { }
Geolocator.isLocationServiceEnabled().then((value) async {
if (value) {
await Geolocator.checkPermission().then((permission) async {
if (permission == LocationPermission.always || permission == LocationPermission.whileInUse) {
Geolocator.getLastKnownPosition().then((value) {
setLocation(value);
if (callBack != null) callBack(LatLng(value?.latitude ?? 24.7101433, value?.longitude ?? 46.6757709));
}).catchError((err) {
if (isShowConfirmDialog && isShowLocationTimeoutDialog) {}
});
}
if (permission == LocationPermission.denied || permission == LocationPermission.deniedForever) { void getLocation(
if (Platform.isAndroid) { {Function(LatLng)? onSuccess, VoidCallback? onFailure}) async {
// Utils.showPermissionConsentDialog(context, TranslationBase.of(context).locationPermissionDialog, () async { if (Platform.isIOS) {
final hasPermission = await _handlePermission(); getCurrentLocation(onFailure: onFailure, onSuccess: onSuccess);
if (hasPermission) { return;
// Geolocator.getCurrentPosition(locationSettings: LocationSettings(accuracy: LocationAccuracy.medium, timeLimit: Duration(seconds: 5))).then((value) { }
Geolocator.getLastKnownPosition().then((value) {
setLocation(value); if (await isGMSDevice ?? true) {
if (callBack != null) callBack(LatLng(value?.latitude ?? 24.7101433, value?.longitude ?? 46.6757709)); getCurrentLocation(onFailure: onFailure, onSuccess: onSuccess);
}); return;
} else { }
// if (isShowConfirmDialog) showErrorLocationDialog(false, failureCallBack: () {});
} getHMSLocation(onFailure: onFailure, onSuccess: onSuccess);
// }); }
} else {
if (await Permission.location.request().isGranted) { void getCurrentLocation(
getCurrentLocation(callBack: callBack); {Function(LatLng)? onSuccess, VoidCallback? onFailure}) async {
} else { var location = Location();
setZeroLocation();
if (isShowConfirmDialog) showErrorLocationDialog(false, failureCallBack: () {}); bool isLocationEnabled = await location.serviceEnabled();
} //if the location service is not enabled, ask the user to enable it
} if (!isLocationEnabled) {
} isLocationEnabled = await location.requestService();
}).catchError((err) {}); if (!isLocationEnabled) {
} else { appState.resetLocation();
if (isShowConfirmDialog) showErrorLocationDialog(false, failureCallBack: () {}); onFailure?.call();
return;
}
}
LocationPermission permissionGranted = await Geolocator.checkPermission();
if (permissionGranted == LocationPermission.denied) {
permissionGranted = await Geolocator.requestPermission();
if (permissionGranted != LocationPermission.whileInUse &&
permissionGranted != LocationPermission.always) {
appState.resetLocation();
onFailure?.call();
return;
} }
}).catchError((err) {}); }
Position? currentLocation = await Geolocator.getLastKnownPosition();
if(currentLocation?.latitude == null || currentLocation?.longitude == null){
currentLocation = await Geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.low);
}
LatLng locationData = LatLng(
currentLocation?.latitude ?? 0.0, currentLocation?.longitude ?? 0.0);
saveLatLngToAppState(locationData);
onSuccess?.call(locationData);
} }
Future<bool> checkIfGPSIsEnabled() async { Future<bool> checkIfGPSIsEnabled() async {
@ -166,4 +191,69 @@ class LocationUtils {
].request(); ].request();
return (result[Permission.location]!.isGranted || result[Permission.locationAlways]!.isGranted); return (result[Permission.location]!.isGranted || result[Permission.locationAlways]!.isGranted);
} }
void saveLatLngToAppState(LatLng locationData) {
appState.userLat = locationData.latitude;
appState.userLong = locationData.longitude;
}
void getHMSLocation(
{VoidCallback? onFailure, Function(LatLng p1)? onSuccess}) async {
try {
var location = Location();
HmsLocation.FusedLocationProviderClient locationService =
HmsLocation.FusedLocationProviderClient()..initFusedLocationService();
bool isLocationEnabled = await Geolocator.isLocationServiceEnabled();
//if the location service is not enabled, ask the user to enable it
if (!isLocationEnabled) {
HmsLocation.LocationRequest locationRequest =
HmsLocation.LocationRequest()
..priority = HmsLocation.LocationRequest.PRIORITY_HIGH_ACCURACY;
HmsLocation.LocationSettingsRequest request =
HmsLocation.LocationSettingsRequest(
alwaysShow: true,
needBle: false,
requests: [locationRequest],
);
await locationService.checkLocationSettings(request);
}
LocationPermission permissionGranted = await Geolocator.checkPermission();
if (permissionGranted == LocationPermission.denied) {
permissionGranted = await Geolocator.requestPermission();
if (permissionGranted != LocationPermission.whileInUse &&
permissionGranted != LocationPermission.always) {
appState.resetLocation();
onFailure?.call();
return;
}
}
HmsLocation.Location data = await locationService.getLastLocation();
if (data.latitude == null || data.longitude == null) {
appState.resetLocation();
HmsLocation.LocationRequest request = HmsLocation.LocationRequest()
..priority = HmsLocation.LocationRequest.PRIORITY_HIGH_ACCURACY
..interval = 1000 // 1 second
..numUpdates = 1;
locationService.requestLocationUpdates(request);
locationService.onLocationData?.listen((location) {
data = location;
if (data.latitude == null || data.longitude == null) {
appState.resetLocation();
onFailure?.call();
return;
}
saveLatLngToAppState(
LatLng(data.latitude ?? 0.0, data.longitude ?? 0.0));
});
}
saveLatLngToAppState(LatLng(data.latitude ?? 0.0, data.longitude ?? 0.0));
} catch (e) {
appState.resetLocation();
onFailure?.call();
}
}
} }

@ -3,6 +3,7 @@ import 'package:flutter/material.dart';
import 'package:hmg_patient_app_new/core/app_state.dart'; import 'package:hmg_patient_app_new/core/app_state.dart';
import 'package:hmg_patient_app_new/core/cache_consts.dart'; import 'package:hmg_patient_app_new/core/cache_consts.dart';
import 'package:hmg_patient_app_new/core/dependencies.dart'; import 'package:hmg_patient_app_new/core/dependencies.dart';
import 'package:hmg_patient_app_new/core/location_util.dart';
import 'package:hmg_patient_app_new/core/utils/date_util.dart'; import 'package:hmg_patient_app_new/core/utils/date_util.dart';
import 'package:hmg_patient_app_new/core/utils/doctor_response_mapper.dart'; import 'package:hmg_patient_app_new/core/utils/doctor_response_mapper.dart';
import 'package:hmg_patient_app_new/core/utils/loading_utils.dart'; import 'package:hmg_patient_app_new/core/utils/loading_utils.dart';
@ -37,6 +38,8 @@ class BookAppointmentsViewModel extends ChangeNotifier {
int initialSlotDuration = 0; int initialSlotDuration = 0;
LocationUtils locationUtils;
List<GetClinicsListResponseModel> clinicsList = []; List<GetClinicsListResponseModel> clinicsList = [];
List<GetClinicsListResponseModel> _filteredClinicsList = []; List<GetClinicsListResponseModel> _filteredClinicsList = [];
@ -74,7 +77,9 @@ class BookAppointmentsViewModel extends ChangeNotifier {
bool shouldLoadSpecificClinic = false; bool shouldLoadSpecificClinic = false;
String? currentlySelectedHospitalFromRegionFlow; String? currentlySelectedHospitalFromRegionFlow;
BookAppointmentsViewModel({required this.bookAppointmentsRepo, required this.errorHandlerService, required this.navigationService, required this.myAppointmentsViewModel}); BookAppointmentsViewModel({required this.bookAppointmentsRepo, required this.errorHandlerService, required this.navigationService, required this.myAppointmentsViewModel, required this.locationUtils}) {;
initBookAppointmentViewModel();
}
void initializeFilteredList() { void initializeFilteredList() {
_filteredClinicsList = List.from(clinicsList); _filteredClinicsList = List.from(clinicsList);
@ -97,6 +102,7 @@ class BookAppointmentsViewModel extends ChangeNotifier {
isDoctorProfileLoading = true; isDoctorProfileLoading = true;
clinicsList.clear(); clinicsList.clear();
doctorsList.clear(); doctorsList.clear();
// getLocation();
notifyListeners(); notifyListeners();
} }
@ -408,10 +414,10 @@ class BookAppointmentsViewModel extends ChangeNotifier {
Future<void> getRegionMappedProjectList() async { Future<void> getRegionMappedProjectList() async {
//todo handle the case in the location is switch on //todo handle the case in the location is switch on
if(hospitalList != null && hospitalList!.registeredDoctorMap != null && hospitalList!.registeredDoctorMap!.isNotEmpty){ // if(hospitalList != null && hospitalList!.registeredDoctorMap != null && hospitalList!.registeredDoctorMap!.isNotEmpty){
filteredHospitalList = hospitalList; // filteredHospitalList = hospitalList;
return; // return;
} // }
isRegionListLoading = true; isRegionListLoading = true;
notifyListeners(); notifyListeners();
final result = await bookAppointmentsRepo.getProjectList(); final result = await bookAppointmentsRepo.getProjectList();
@ -429,10 +435,8 @@ class BookAppointmentsViewModel extends ChangeNotifier {
lat: _appState.userLat, lat: _appState.userLat,
lng: _appState.userLong, lng: _appState.userLong,
); );
var lat = await Utils.getNumFromPrefs(CacheConst.userLat);
var lng = await Utils.getNumFromPrefs(CacheConst.userLong); var isLocationEnabled = (_appState.userLat != 0) && (_appState.userLong != 0);
var isLocationEnabled = (lat != 0) && (lng != 0);
hospitalList = hospitalList =
await DoctorMapper.sortList(isLocationEnabled, hospitalList!); await DoctorMapper.sortList(isLocationEnabled, hospitalList!);
@ -480,15 +484,15 @@ class BookAppointmentsViewModel extends ChangeNotifier {
notifyListeners(); notifyListeners();
} }
Future<bool> isLocationEnabled() async{ bool isLocationEnabled() {
return await Location().serviceEnabled(); return _appState.userLong != 0.0 && _appState.userLong != 0.0;
} }
bool getLocationStatus() { // bool getLocationStatus() {
bool isLocationAvaiable = false; // bool isLocationAvaiable = false;
isLocationEnabled().then((value) => isLocationAvaiable = value); // isLocationEnabled().then((value) => isLocationAvaiable = value);
return isLocationAvaiable; // return isLocationAvaiable;
} // }
void setLoadSpecificClinic(bool status) { void setLoadSpecificClinic(bool status) {
shouldLoadSpecificClinic = status; shouldLoadSpecificClinic = status;
@ -518,4 +522,9 @@ class BookAppointmentsViewModel extends ChangeNotifier {
void resetFilterList(){ void resetFilterList(){
filteredHospitalList = hospitalList; filteredHospitalList = hospitalList;
} }
void getLocation(){
locationUtils.getLocation();
}
} }

@ -132,6 +132,7 @@ void main() async {
errorHandlerService: getIt(), errorHandlerService: getIt(),
navigationService: getIt(), navigationService: getIt(),
myAppointmentsViewModel: getIt(), myAppointmentsViewModel: getIt(),
locationUtils: getIt(),
), ),
), ),
ChangeNotifierProvider<AuthenticationViewModel>( ChangeNotifierProvider<AuthenticationViewModel>(

@ -51,7 +51,7 @@ class AppointmentCheckinBottomSheet extends StatelessWidget {
// navigationService: myAppointmentsViewModel.navigationService, // navigationService: myAppointmentsViewModel.navigationService,
// appState: myAppointmentsViewModel.appState, // appState: myAppointmentsViewModel.appState,
// ); // );
locationUtils.getCurrentLocation(callBack: (value) { locationUtils.getCurrentLocation(onSuccess: (value) {
projectDetailListModel = Utils.getProjectDetailObj(_appState, patientAppointmentHistoryResponseModel.projectID); projectDetailListModel = Utils.getProjectDetailObj(_appState, patientAppointmentHistoryResponseModel.projectID);
double dist = Utils.distance(value.latitude, value.longitude, double.parse(projectDetailListModel.latitude!), double.parse(projectDetailListModel.longitude!)).ceilToDouble() * 1000; double dist = Utils.distance(value.latitude, value.longitude, double.parse(projectDetailListModel.latitude!), double.parse(projectDetailListModel.longitude!)).ceilToDouble() * 1000;
print(dist); print(dist);

@ -93,7 +93,7 @@ class HospitalBottomSheetBody extends StatelessWidget {
?.hmcDoctorList?[index]; ?.hmcDoctorList?[index];
return HospitalListItem( return HospitalListItem(
hospitalData: hospital, hospitalData: hospital,
isLocationEnabled: appointmentsViewModel.getLocationStatus(), isLocationEnabled: appointmentsViewModel.isLocationEnabled(),
).onPress(() { ).onPress(() {
regionalViewModel.setHospitalModel(hospital); regionalViewModel.setHospitalModel(hospital);
regionalViewModel.setBottomSheetState(AppointmentViaRegionState.CLINIC_SELECTION); regionalViewModel.setBottomSheetState(AppointmentViaRegionState.CLINIC_SELECTION);

@ -44,6 +44,7 @@ class _BookAppointmentPageState extends State<BookAppointmentPage> {
void initState() { void initState() {
scheduleMicrotask(() { scheduleMicrotask(() {
bookAppointmentsViewModel.initBookAppointmentViewModel(); bookAppointmentsViewModel.initBookAppointmentViewModel();
bookAppointmentsViewModel.getLocation();
}); });
super.initState(); super.initState();
} }

@ -83,6 +83,8 @@ dependencies:
family_bottom_sheet: ^0.1.0 family_bottom_sheet: ^0.1.0
location: ^8.0.1 location: ^8.0.1
gms_check: ^1.0.4
huawei_location: ^6.14.2+301
dev_dependencies: dev_dependencies:
flutter_test: flutter_test:

Loading…
Cancel
Save