From f669adcb9dc6c49c040fed27963487c4f7800910 Mon Sep 17 00:00:00 2001 From: haroon amjad Date: Tue, 1 Sep 2020 16:38:04 +0300 Subject: [PATCH] Location service implemented --- lib/config/localized_values.dart | 3 +- lib/config/shared_pref_kay.dart | 2 + .../Appointments/DoctorListResponse.dart | 2 +- lib/pages/BookAppointment/BookingOptions.dart | 27 ++- lib/pages/BookAppointment/Search.dart | 6 +- lib/pages/BookAppointment/SearchResults.dart | 60 +++++-- .../components/SearchByClinic.dart | 49 +++-- .../BookAppointment/widgets/BranchView.dart | 18 +- .../BookAppointment/widgets/DoctorView.dart | 4 +- lib/pages/livecare/widgets/clinic_list.dart | 169 +++++++++--------- .../appointment_services/GetDoctorsList.dart | 12 +- lib/uitl/location_util.dart | 69 +++++++ lib/uitl/translations_delegate_base.dart | 2 + 13 files changed, 287 insertions(+), 136 deletions(-) create mode 100644 lib/uitl/location_util.dart diff --git a/lib/config/localized_values.dart b/lib/config/localized_values.dart index 35d24cc7..c6c109f3 100644 --- a/lib/config/localized_values.dart +++ b/lib/config/localized_values.dart @@ -362,5 +362,6 @@ const Map> localizedValues = { "medicalProfile": {"en": "Medical Profile", 'ar': 'الملف الطبي'}, "consultation": {"en": "Consultation", "ar": "استشارة"}, "logs": {"en": "Logs", "ar": "السجلات"}, - "textToSpeech": {"en": "How May I Help You?", "ar": "كيف يمكنني مساعدتك؟"} + "textToSpeech": {"en": "How May I Help You?", "ar": "كيف يمكنني مساعدتك؟"}, + "locationDialogMessage": {"en": "Allow the HMG app to access your location will assist you in showing the hospitals according to the nearest to you.", "ar": "السماح لتطبيق مجموعة الحبيب الطبية بالوصول إلى موقعك سيساعدك في إظهار المستشفيات وفقًا للأقرب إليك."} }; diff --git a/lib/config/shared_pref_kay.dart b/lib/config/shared_pref_kay.dart index 414c6a80..68df4e75 100644 --- a/lib/config/shared_pref_kay.dart +++ b/lib/config/shared_pref_kay.dart @@ -11,3 +11,5 @@ const AUTH_DATA = 'auth-data'; const IMEI_USER_DATA = 'imei-user-data'; const NHIC_DATA = 'nhic-data'; const FAMILY_FILE = 'family-file'; +const USER_LAT = 'user-lat'; +const USER_LONG = 'user-long'; \ No newline at end of file diff --git a/lib/models/Appointments/DoctorListResponse.dart b/lib/models/Appointments/DoctorListResponse.dart index 2f4ee2a0..07563a25 100644 --- a/lib/models/Appointments/DoctorListResponse.dart +++ b/lib/models/Appointments/DoctorListResponse.dart @@ -30,7 +30,7 @@ class DoctorList { int noOfPatientsRate; int originalClinicID; int personRate; - int projectDistanceInKiloMeters; + dynamic projectDistanceInKiloMeters; String qR; dynamic qRString; int rateNumber; diff --git a/lib/pages/BookAppointment/BookingOptions.dart b/lib/pages/BookAppointment/BookingOptions.dart index dacb25e9..b6dc5500 100644 --- a/lib/pages/BookAppointment/BookingOptions.dart +++ b/lib/pages/BookAppointment/BookingOptions.dart @@ -1,19 +1,36 @@ import 'package:diplomaticquarterapp/pages/BookAppointment/widgets/CardCommon.dart'; -import 'package:diplomaticquarterapp/services/robo_search/search_provider.dart'; +import 'package:diplomaticquarterapp/uitl/location_util.dart'; import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart'; import 'package:flutter/material.dart'; -import 'package:provider/provider.dart'; import '../../uitl/translations_delegate_base.dart'; -class BookingOptions extends StatelessWidget { +class BookingOptions extends StatefulWidget { final bool isAppbar; + BookingOptions({this.isAppbar = false}); + + @override + _BookingOptionsState createState() => _BookingOptionsState(); +} + +class _BookingOptionsState extends State { + LocationUtils locationUtils; + + @override + void initState() { + locationUtils = + new LocationUtils(isShowConfirmDialog: true, context: context); + WidgetsBinding.instance + .addPostFrameCallback((_) => locationUtils.getCurrentLocation()); + + super.initState(); + } + @override Widget build(BuildContext context) { - final searchValue = Provider.of(context); return AppScaffold( - isShowAppBar: isAppbar, + isShowAppBar: widget.isAppbar, appBarTitle: TranslationBase.of(context).bookAppo, body: Container( margin: EdgeInsets.fromLTRB(10.0, 20.0, 10.0, 10.0), diff --git a/lib/pages/BookAppointment/Search.dart b/lib/pages/BookAppointment/Search.dart index 9af6b449..08b49462 100644 --- a/lib/pages/BookAppointment/Search.dart +++ b/lib/pages/BookAppointment/Search.dart @@ -1,13 +1,17 @@ import 'package:diplomaticquarterapp/pages/BookAppointment/components/SearchByClinic.dart'; import 'package:diplomaticquarterapp/pages/BookAppointment/components/SearchByDoctor.dart'; +import 'package:diplomaticquarterapp/uitl/location_util.dart'; import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart'; +import 'package:diplomaticquarterapp/widgets/dialogs/confirm_dialog.dart'; import 'package:diplomaticquarterapp/widgets/others/bottom_bar.dart'; -import 'package:diplomaticquarterapp/widgets/others/floating_button_search.dart'; import 'package:flutter/material.dart'; +import 'package:geolocator/geolocator.dart'; class Search extends StatefulWidget { final int type; + Search({this.type = 0}); + @override _SearchState createState() => _SearchState(); } diff --git a/lib/pages/BookAppointment/SearchResults.dart b/lib/pages/BookAppointment/SearchResults.dart index 7da5112b..5d74cc59 100644 --- a/lib/pages/BookAppointment/SearchResults.dart +++ b/lib/pages/BookAppointment/SearchResults.dart @@ -1,11 +1,11 @@ import 'package:diplomaticquarterapp/models/Appointments/DoctorListResponse.dart'; +import 'package:diplomaticquarterapp/pages/BookAppointment/widgets/DoctorView.dart'; import 'package:diplomaticquarterapp/services/robo_search/event_provider.dart'; import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart'; +import 'package:diplomaticquarterapp/widgets/others/app_expandable_notifier.dart'; import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart'; import 'package:flutter/material.dart'; -import 'widgets/DoctorView.dart'; - class SearchResults extends StatefulWidget { List doctorsList = []; @@ -49,19 +49,51 @@ class _SearchResultsState extends State { body: Container( margin: EdgeInsets.only(bottom: 10.0), child: SingleChildScrollView( - child: ListView.builder( - scrollDirection: Axis.vertical, - shrinkWrap: true, - physics: ScrollPhysics(), - padding: EdgeInsets.all(0.0), - itemCount: widget.doctorsList.length, - itemBuilder: (context, index) { - return DoctorView( - //AJ note - doctor: widget.doctorsList[index], - ); - }, + physics: BouncingScrollPhysics(), + child: FractionallySizedBox( + widthFactor: 1.0, + child: Column( + children: [ + ...List.generate( + widget.doctorsList.length, + (index) => AppExpandableNotifier( + title: widget.doctorsList[index].projectName, + bodyWidget: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: widget.doctorsList.map((doctorObj) { + return DoctorView( + doctor: doctorObj, + ); + }).toList(), + ), + ), + ) + ], + ), ), + +// ListView.builder( +// scrollDirection: Axis.vertical, +// shrinkWrap: true, +// physics: ScrollPhysics(), +// padding: EdgeInsets.all(0.0), +// itemCount: widget.doctorsList.length, +// itemBuilder: (context, index) { +// return AppExpandableNotifier( +// title: widget.doctorsList[index].projectName, +// bodyWidget: Column( +// crossAxisAlignment: CrossAxisAlignment.start, +// mainAxisAlignment: MainAxisAlignment.spaceBetween, +// children: widget.doctorsList.map((labOrder) { +// return DoctorView( +// doctor: widget.doctorsList[index], +// ); +// }).toList(), +// ), +// ); +// }, +// ), ), ), ); diff --git a/lib/pages/BookAppointment/components/SearchByClinic.dart b/lib/pages/BookAppointment/components/SearchByClinic.dart index bfadd3b0..2188d296 100644 --- a/lib/pages/BookAppointment/components/SearchByClinic.dart +++ b/lib/pages/BookAppointment/components/SearchByClinic.dart @@ -1,4 +1,4 @@ -import 'dart:convert'; +import "dart:collection"; import 'package:diplomaticquarterapp/models/Appointments/DoctorListResponse.dart'; import 'package:diplomaticquarterapp/models/Clinics/ClinicListResponse.dart'; @@ -6,16 +6,11 @@ import 'package:diplomaticquarterapp/pages/BookAppointment/widgets/BranchView.da import 'package:diplomaticquarterapp/services/appointment_services/GetDoctorsList.dart'; import 'package:diplomaticquarterapp/services/clinic_services/get_clinic_service.dart'; import 'package:diplomaticquarterapp/services/robo_search/event_provider.dart'; -import 'package:diplomaticquarterapp/services/robo_search/search_provider.dart'; import 'package:diplomaticquarterapp/uitl/app_toast.dart'; import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart'; import 'package:flutter/material.dart'; -import 'package:provider/provider.dart'; import 'package:smart_progress_bar/smart_progress_bar.dart'; -import '../SearchResults.dart'; -import "dart:collection"; - class SearchByClinic extends StatefulWidget { @override _SearchByClinicState createState() => _SearchByClinicState(); @@ -30,14 +25,6 @@ class _SearchByClinicState extends State { @override void initState() { WidgetsBinding.instance.addPostFrameCallback((_) => getClinicsList()); - // event.controller.stream.listen((p) { - // if (p['clinic_id'] != null) { - // // setState(() { - // dropdownValue = p['clinic_id'].toString(); - // //}); - // getDoctorsList(context); - // } - // }); super.initState(); } @@ -118,36 +105,43 @@ class _SearchByClinicState extends State { getDoctorsList(BuildContext context) { List doctorsList = []; - //======================== List arr = []; + List arrDistance = []; var distinctIds; List result; int numAll; - //========================= DoctorsListService service = new DoctorsListService(); service.getDoctorsList(int.parse(dropdownValue), 0, context).then((res) { if (res['MessageStatus'] == 1) { setState(() { if (res['DoctorList'].length != 0) { + print(res['DoctorList']); doctorsList.clear(); res['DoctorList'].forEach((v) { doctorsList.add(new DoctorList.fromJson(v)); arr.add(new DoctorList.fromJson(v).projectName); - // print(DoctorList.fromJson(v).projectName); - // print(DoctorList.fromJson(v).projectDistanceInKiloMeters); - // distinctIds = result.toSet().toList(); + arrDistance.add(new DoctorList.fromJson(v) + .projectDistanceInKiloMeters + .toString()); + +// print(DoctorList +// .fromJson(v) +// .projectName); +// print(DoctorList +// .fromJson(v) +// .projectDistanceInKiloMeters); +// distinctIds = result.toSet().toList(); }); } else {} }); result = LinkedHashSet.from(arr).toList(); numAll = result.length; - // print(result); - print("numAll=" + numAll.toString()); - navigateToSearchResults(context, doctorsList, result, numAll); + navigateToSearchResults( + context, doctorsList, result, numAll, arrDistance); } else { AppToast.showErrorToast(message: res['ErrorEndUserMessage']); } @@ -157,12 +151,17 @@ class _SearchByClinicState extends State { text: "Loading", backgroundColor: Colors.blue.withOpacity(0.6)); } - Future navigateToSearchResults(context, docList, result, numAll) async { + Future navigateToSearchResults( + context, docList, result, numAll, resultDistance) async { Navigator.push( context, MaterialPageRoute( - builder: (context) => - BranchView(doctorsList: docList, result: result, num: numAll), +// builder: (context) => SearchResults(doctorsList: docList) + builder: (context) => BranchView( + doctorsList: docList, + result: result, + num: numAll, + resultDistance: resultDistance), ), ); //builder: (context) => SearchResults(doctorsList: docList))); diff --git a/lib/pages/BookAppointment/widgets/BranchView.dart b/lib/pages/BookAppointment/widgets/BranchView.dart index ecf2bfd6..da069b75 100644 --- a/lib/pages/BookAppointment/widgets/BranchView.dart +++ b/lib/pages/BookAppointment/widgets/BranchView.dart @@ -10,9 +10,11 @@ class BranchView extends StatefulWidget { final List doctorsList; final List result; + final List resultDistance; final int num; - const BranchView({Key key, this.doctorsList, this.result, this.num}) + const BranchView( + {Key key, this.doctorsList, this.result, this.resultDistance, this.num}) : super(key: key); @override @@ -29,6 +31,7 @@ class _BranchViewState extends State { itemBuilder: (BuildContext context, int index) { return new ExpandableListView( result2: widget.result, + resultDistance: widget.resultDistance, val: index, doctorsList2: widget.doctorsList); }, @@ -40,10 +43,12 @@ class _BranchViewState extends State { class ExpandableListView extends StatefulWidget { final List result2; + final List resultDistance; final List doctorsList2; final val; - const ExpandableListView({Key key, this.result2, this.val, this.doctorsList2}) + const ExpandableListView( + {Key key, this.result2, this.resultDistance, this.val, this.doctorsList2}) : super(key: key); @override @@ -76,7 +81,11 @@ class _ExpandableListViewState extends State { mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ new Text( - widget.result2[widget.val].toString() + " " + " - 22 KM", + widget.result2[widget.val].toString() + + " " + + " - " + + widget.resultDistance[widget.val].toString() + + " KM", style: new TextStyle( fontWeight: FontWeight.bold, color: Colors.black), ), @@ -156,8 +165,7 @@ class ExpandableContainer extends StatelessWidget { duration: new Duration(milliseconds: 500), curve: Curves.easeInOut, width: screenWidth, - height: - expanded ? expandedHeight : collapsedHeight, + height: expanded ? MediaQuery.of(context).size.height : collapsedHeight, child: new Container( child: child, decoration: new BoxDecoration( diff --git a/lib/pages/BookAppointment/widgets/DoctorView.dart b/lib/pages/BookAppointment/widgets/DoctorView.dart index 39e4ab36..e8f08af5 100644 --- a/lib/pages/BookAppointment/widgets/DoctorView.dart +++ b/lib/pages/BookAppointment/widgets/DoctorView.dart @@ -21,7 +21,7 @@ class DoctorView extends StatelessWidget { getDoctorsProfile(context, doctor); }, child: Card( - margin: EdgeInsets.fromLTRB(20.0, 16.0, 20.0, 8.0), + margin: EdgeInsets.fromLTRB(10.0, 16.0, 10.0, 8.0), color: Colors.white, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10), @@ -39,7 +39,7 @@ class DoctorView extends StatelessWidget { fit: BoxFit.fill, height: 60.0, width: 60.0), ), Container( - width: MediaQuery.of(context).size.width * 0.52, + width: MediaQuery.of(context).size.width * 0.5, margin: EdgeInsets.fromLTRB(20.0, 10.0, 10.0, 0.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, diff --git a/lib/pages/livecare/widgets/clinic_list.dart b/lib/pages/livecare/widgets/clinic_list.dart index 77c3e741..9100a64e 100644 --- a/lib/pages/livecare/widgets/clinic_list.dart +++ b/lib/pages/livecare/widgets/clinic_list.dart @@ -14,7 +14,6 @@ import 'package:diplomaticquarterapp/uitl/app_shared_preferences.dart'; import 'package:diplomaticquarterapp/uitl/app_toast.dart'; import 'package:diplomaticquarterapp/uitl/utils.dart'; import 'package:diplomaticquarterapp/widgets/in_app_browser/InAppBrowser.dart'; -import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart'; import 'package:flutter/material.dart'; import 'package:smart_progress_bar/smart_progress_bar.dart'; @@ -49,7 +48,7 @@ class _clinic_listState extends State { liveCareClinicsListResponse = new LiveCareClinicsListResponse(); WidgetsBinding.instance.addPostFrameCallback((_) { // Future.delayed(new Duration(milliseconds: 1200), () { - getLiveCareClinicsList(); + getLiveCareClinicsList(); // }); }); getLanguageID(); @@ -58,79 +57,82 @@ class _clinic_listState extends State { @override Widget build(BuildContext context) { - return AppScaffold( - isShowAppBar: false, - body: SingleChildScrollView( - child: isDataLoaded - ? Container( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Container( - margin: EdgeInsets.all(15.0), - child: Text("Online Clinics: ", - style: TextStyle( - fontSize: 20.0, fontWeight: FontWeight.bold)), - ), - ListView.builder( - scrollDirection: Axis.vertical, - shrinkWrap: true, - physics: ScrollPhysics(), - padding: EdgeInsets.all(0.0), - itemCount: liveCareClinicsListResponse - .patientERGetClinicsList.length, - itemBuilder: (context, index) { - return InkWell( - onTap: () { - updateSelectedIndex(liveCareClinicsListResponse - .patientERGetClinicsList[index]); - }, - child: ClinicCard( - isSelected: selectedClinicID == - liveCareClinicsListResponse - .patientERGetClinicsList[index] - .serviceID - ? true - : false, - patientERGetClinicsList: liveCareClinicsListResponse - .patientERGetClinicsList[index], - languageID: languageID, - ), - ); - }, - ), - Container( - height: 80.0, - ), - ], - ), - ) - : Container(), - ), - bottomSheet: Container( - width: MediaQuery.of(context).size.width, - height: 50.0, - margin: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0), - child: ButtonTheme( - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(10.0), - ), - minWidth: MediaQuery.of(context).size.width * 0.7, - height: 45.0, - child: RaisedButton( - color: new Color(0xFF60686b), - textColor: Colors.white, - disabledTextColor: Colors.white, - disabledColor: new Color(0xFFbcc2c4), - onPressed: startLiveCare, - child: Text("Start", style: TextStyle(fontSize: 18.0)), - ), - ), + return SingleChildScrollView( + child: Column( + children: [ + isDataLoaded + ? Container( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Container( + margin: EdgeInsets.all(15.0), + child: Text("Online Clinics: ", + style: TextStyle( + fontSize: 20.0, fontWeight: FontWeight.bold)), + ), + ListView.builder( + scrollDirection: Axis.vertical, + shrinkWrap: true, + physics: ScrollPhysics(), + padding: EdgeInsets.all(0.0), + itemCount: liveCareClinicsListResponse + .patientERGetClinicsList.length, + itemBuilder: (context, index) { + return InkWell( + onTap: () { + updateSelectedIndex(liveCareClinicsListResponse + .patientERGetClinicsList[index]); + }, + child: ClinicCard( + isSelected: selectedClinicID == + liveCareClinicsListResponse + .patientERGetClinicsList[index] + .serviceID + ? true + : false, + patientERGetClinicsList: + liveCareClinicsListResponse + .patientERGetClinicsList[index], + languageID: languageID, + ), + ); + }, + ), + Container( + height: 10.0, + ), + ], + ), + ) + : Container(), + isDataLoaded ? Container( + width: MediaQuery.of(context).size.width, + height: 50.0, + margin: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0), + child: ButtonTheme( + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(10.0), + ), + minWidth: MediaQuery.of(context).size.width * 0.7, + height: 45.0, + child: RaisedButton( + color: new Color(0xFF60686b), + textColor: Colors.white, + disabledTextColor: Colors.white, + disabledColor: new Color(0xFFbcc2c4), + onPressed: startLiveCare, + child: Text("Start", style: TextStyle(fontSize: 18.0)), + ), + ), + ) : Container(), + ], ), ); } void startLiveCare() { + bool isError = false; LiveCareService service = new LiveCareService(); ERAppointmentFeesResponse erAppointmentFeesResponse = new ERAppointmentFeesResponse(); @@ -141,12 +143,15 @@ class _clinic_listState extends State { }) .catchError((err) { print(err); + isError = true; + AppToast.showErrorToast(message: err); }) .showProgressBar( text: "Loading", backgroundColor: Colors.blue.withOpacity(0.6)) .then((value) { - getERAppointmentTime( - erAppointmentFeesResponse.getERAppointmentFeesList); + if (!isError) + getERAppointmentTime( + erAppointmentFeesResponse.getERAppointmentFeesList); }); } @@ -158,6 +163,7 @@ class _clinic_listState extends State { getERAppointmentFeesList, res['WatingtimeInteger']); }).catchError((err) { print(err); + AppToast.showErrorToast(message: err); }).showProgressBar( text: "Loading", backgroundColor: Colors.blue.withOpacity(0.6)); } @@ -339,14 +345,17 @@ class _clinic_listState extends State { service .addNewCallForPatientER(selectedClinicID, clientRequestID, context) .then((res) { - AppToast.showSuccessToast( - message: "New Call has been added successfully"); - }).catchError((err) { - print(err); - }).showProgressBar( - text: "Loading", backgroundColor: Colors.blue.withOpacity(0.6)).then((value) { - widget.getLiveCareHistory(); - }); + AppToast.showSuccessToast( + message: "New Call has been added successfully"); + }) + .catchError((err) { + print(err); + }) + .showProgressBar( + text: "Loading", backgroundColor: Colors.blue.withOpacity(0.6)) + .then((value) { + widget.getLiveCareHistory(); + }); } getLanguageID() async { diff --git a/lib/services/appointment_services/GetDoctorsList.dart b/lib/services/appointment_services/GetDoctorsList.dart index ba3ad56e..27a66d43 100644 --- a/lib/services/appointment_services/GetDoctorsList.dart +++ b/lib/services/appointment_services/GetDoctorsList.dart @@ -20,6 +20,9 @@ class DoctorsListService extends BaseService { AuthenticatedUser authUser = new AuthenticatedUser(); AuthProvider authProvider = new AuthProvider(); + double lat; + double long; + Future getDoctorsList(int clinicID, int projectID, BuildContext context, {doctorId}) async { //Utils.showProgressDialog(context); @@ -31,6 +34,11 @@ class DoctorsListService extends BaseService { authUser = data; } + if (await this.sharedPref.getDouble(USER_LAT) != null && await this.sharedPref.getDouble(USER_LONG) != null) { + lat = await this.sharedPref.getDouble(USER_LAT); + long = await this.sharedPref.getDouble(USER_LONG); + } + var languageID = await sharedPref.getString(APP_LANGUAGE); Request req = appGlobal.getPublicRequest(); request = { @@ -52,8 +60,8 @@ class DoctorsListService extends BaseService { "gender": authUser.gender != null ? authUser.gender : 0, "age": authUser.age != null ? authUser.age : 0, "IsGetNearAppointment": false, - "Latitude": 0, - "Longitude": 0, + "Latitude": lat.toString(), + "Longitude": long.toString(), "License": true }; diff --git a/lib/uitl/location_util.dart b/lib/uitl/location_util.dart new file mode 100644 index 00000000..e3012734 --- /dev/null +++ b/lib/uitl/location_util.dart @@ -0,0 +1,69 @@ +import 'package:diplomaticquarterapp/config/shared_pref_kay.dart'; +import 'package:diplomaticquarterapp/uitl/app_shared_preferences.dart'; +import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart'; +import 'package:diplomaticquarterapp/widgets/dialogs/confirm_dialog.dart'; +import 'package:flutter/cupertino.dart'; +import 'package:geolocator/geolocator.dart'; + +class LocationUtils { + AppSharedPreferences sharedPref = new AppSharedPreferences(); + + bool isShowConfirmDialog; + BuildContext context; + + LocationUtils({@required this.isShowConfirmDialog, @required this.context}); + + void getCurrentLocation() async { + print("current location"); + isLocationServiceEnabled().then((value) { + if (value) { + checkPermission().then((permission) { + if (permission == LocationPermission.always || + permission == LocationPermission.whileInUse) { + getLastKnownPosition().then((value) => setLocation(value)); + } + + if (permission == LocationPermission.denied || + permission == LocationPermission.deniedForever) { + setZeroLocation(); + if (isShowConfirmDialog) showErrorLocationDialog(false); + } + }).catchError((err) { + print(err); + }); + } else { + if (isShowConfirmDialog) showErrorLocationDialog(false); + } + }).catchError((err) { + print(err); + }); + } + + showErrorLocationDialog(bool isPermissionError) { + ConfirmDialog dialog = new ConfirmDialog( + context: context, + confirmMessage: TranslationBase.of(context).locationDialogMessage, + okText: TranslationBase.of(context).confirm, + cancelText: TranslationBase.of(context).cancel_nocaps, + okFunction: () => { + ConfirmDialog.closeAlertDialog(context), + if (isPermissionError) + openAppSettings() + else + openLocationSettings() + }, + cancelFunction: () => {}); + return dialog.showAlertDialog(context); + } + + void setLocation(Position position) { + print(position); + this.sharedPref.setDouble(USER_LAT, position.latitude); + this.sharedPref.setDouble(USER_LONG, position.longitude); + } + + void setZeroLocation() { + this.sharedPref.setDouble(USER_LAT, 0.0); + this.sharedPref.setDouble(USER_LONG, 0.0); + } +} diff --git a/lib/uitl/translations_delegate_base.dart b/lib/uitl/translations_delegate_base.dart index df1999bb..fc1bd800 100644 --- a/lib/uitl/translations_delegate_base.dart +++ b/lib/uitl/translations_delegate_base.dart @@ -449,6 +449,8 @@ class TranslationBase { String get logs => localizedValues['logs'][locale.languageCode]; String get textToSpeech => localizedValues['textToSpeech'][locale.languageCode]; + String get locationDialogMessage => + localizedValues['locationDialogMessage'][locale.languageCode]; } class TranslationBaseDelegate extends LocalizationsDelegate {