import 'dart:convert'; import 'dart:io'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:geolocator/geolocator.dart'; import 'package:healthcare_user/common/settings.dart'; import 'package:healthcare_user/models/pharmacies_model.dart'; import 'package:healthcare_user/prescriptions/add_prescriptions.dart'; import 'package:image_picker/image_picker.dart'; import 'package:healthcare_user/models/prescriptions_model.dart'; class Prescriptions extends StatefulWidget { const Prescriptions({Key? key}) : super(key: key); @override State createState() => _PrescriptionsState(); } class _PrescriptionsState extends State { final ImagePicker _picker = ImagePicker(); String Url = ''; List pharmaciesList = []; List prescriptionsList = []; List FilteredList = []; bool isPharmacyDataLoading = false; bool isPrescriptionsData = false; bool isSereverIssue = false; double lat = 0; double lng = 0; String userAddress = ''; String dropdownArea = '2'; //String dropdownType = 'Tank'; var AreaItems = ['2', '5', '10', '25', '50', '100']; List pharmaciesCheckboxes = []; Future getAllPharmaciesData(var distance) async { isPharmacyDataLoading=true; try { var pharmacyResponse = await AppSettings.getAllpharmacies(); setState(() { pharmaciesList = ((jsonDecode(pharmacyResponse)['data']) as List) .map((dynamic model) { return PharmaciesModel.fromJson(model); }).toList(); FilteredList = []; pharmaciesList.forEach((element) async { var distanceInM; if (distance == '2') { distanceInM = 2000; } else if (distance == '5') { distanceInM = 5000; } else if (distance == '10') { distanceInM = 10000; } else if (distance == '25') { distanceInM = 25000; } else if (distance == '50') { distanceInM = 50000; } else if (distance == '100') { distanceInM = 100000; } double distanceInMeters = await Geolocator.distanceBetween( element.lat, element.lng, lat, lng); if (distanceInMeters <= distanceInM) { FilteredList.add(element); } }); isPharmacyDataLoading = false; }); } catch (e) { setState(() { isPharmacyDataLoading = false; isSereverIssue = true; }); } } Future getAllPrescriptions() async { isPrescriptionsData=true; try { var response = await AppSettings.getAllPrescriptions(); setState(() { prescriptionsList = ((jsonDecode(response)) as List) .map((dynamic model) { return PrescriptionsModel.fromJson(model); }).toList(); isPrescriptionsData = false; }); } catch (e) { setState(() { isPrescriptionsData = false; isSereverIssue = true; }); } } @override void initState() { lat = AppSettings.userLatitude; lng = AppSettings.userLongitude; userAddress = AppSettings.userAddress; getAllPrescriptions(); //getAllPharmaciesData(dropdownArea); super.initState(); } Future pickImageFromGallery() async { try { final image = await _picker.pickImage(source: ImageSource.gallery); if (image == null) return; final imageTemp = File(image.path); AppSettings.preLoaderDialog(context); var res = await AppSettings.uploadImageHTTPForPrescriptions(image); print(jsonDecode(res)); Navigator.of(context, rootNavigator: true).pop(); setState(() { Url = jsonDecode(res)['pictures'][0]; }); } on PlatformException catch (e) { print('Failed to pick image: $e'); } } Future takeImageFromCamera() async { try { final image = await _picker.pickImage(source: ImageSource.camera); if (image == null) return; final imageTemp = File(image.path); AppSettings.preLoaderDialog(context); var res = await AppSettings.uploadImageHTTPForPrescriptions(image); print(jsonDecode(res)); Navigator.of(context, rootNavigator: true).pop(); setState(() { Url = jsonDecode(res)['pictures'][0]; }); } on PlatformException catch (e) { print('Failed to pick image: $e'); } } Widget _pharamciesData() { if (FilteredList.length != 0) { return Column( children: [ GridView.builder( shrinkWrap: true, physics: NeverScrollableScrollPhysics(), itemCount: FilteredList.length, itemBuilder: (context, index) { return Card( elevation: 2.0, child: CheckboxListTile( title: Padding( padding: EdgeInsets.fromLTRB(10, 10, 0, 0), child: Row( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: [ Container( width: MediaQuery.of(context).size.width * .18, height: MediaQuery.of(context).size.height * .10, decoration: BoxDecoration( shape: BoxShape.rectangle, image: DecorationImage( image: FilteredList[index].picture == '' ? AssetImage("images/logo.png") : NetworkImage( FilteredList[index].picture) as ImageProvider, // picked file fit: BoxFit.contain)), ), SizedBox( width: 5, ), Expanded( child: Container( width: MediaQuery.of(context).size.width * .70, child: Column( mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( FilteredList[index] .pharmacy_name .toUpperCase(), style: wrapTextStyleBlack()), SizedBox( height: 10, ), Text( FilteredList[index] .contact_number .toUpperCase(), style: wrapTextStyleBlack()), /*Visibility( visible: FilteredList[index].supplier_alternate_phone_number!='', child: Text( FilteredList[index] .supplier_alternate_phone_number .toUpperCase(), style: wrapTextStyleBlack()),),*/ SizedBox( height: 10, ), Text( FilteredList[index] .pharmacy_address .toUpperCase(), style: wrapTextStyleBlack()), Visibility( visible: FilteredList[index].description != '', child: SizedBox( height: 10, ), ), Visibility( visible: FilteredList[index].description != '', child: Text( FilteredList[index] .description .toUpperCase(), style: wrapTextStyleBlack()), ), SizedBox( height: 10, ), /*Text( FilteredList[index] .starting_price .toUpperCase(), style: wrapTextStyleBlack()), SizedBox(height: 10,),*/ ], )), ), ], ) ), checkColor: Colors.white, activeColor: primaryColor, value: FilteredList[index].isChecked, onChanged: (val) { setState( () { FilteredList[index].isChecked = val!; }, ); if (FilteredList[index].isChecked) { pharmaciesCheckboxes.add({ 'pharmacyId': FilteredList[index] .pharmacy_id, }); } else { pharmaciesCheckboxes.removeWhere((e) => e['pharmacyId'] .toString() .toUpperCase() == FilteredList[index] .pharmacy_id .toString() .toUpperCase()); } }, ), ); }, gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 1,//.size.width * .33, childAspectRatio: MediaQuery.of(context).size.width / (MediaQuery.of(context).size.height /7)), ), ElevatedButton( style: ElevatedButton.styleFrom( primary: primaryColor, // background onPrimary: Colors.white, // foreground ), onPressed: () async { if(Url!=''&&pharmaciesCheckboxes.isNotEmpty){ AppSettings.preLoaderDialog(context); var payload = new Map(); payload["picture"] = Url.toString(); payload["pharmacies"] = pharmaciesCheckboxes; bool status = await AppSettings.uploadPrescription(payload); try { if (status) { Navigator.of(context, rootNavigator: true).pop(); Url=''; pharmaciesCheckboxes = []; AppSettings.longSuccessToast( "Prescription uploaded Successfully"); // Navigator.pop(context); getAllPharmaciesData(dropdownArea); /* Navigator.push( context, MaterialPageRoute( builder: (context) => ConnectionsView()), );*/ } else { Navigator.of(context, rootNavigator: true).pop(); AppSettings.longFailedToast( "Failed to upload prescription"); } } catch (exception) { AppSettings.longFailedToast("Failed to upload prescription"); print(exception); } } else{ AppSettings.longFailedToast('Please select image and pharmacies' ); } }, child: const Text('Upload'), ) ], ); } else { return Center( child: Padding( padding: EdgeInsets.fromLTRB(0, 40, 0, 0), child: isSereverIssue ? Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Image( image: AssetImage('images/serverissue.png'), // height: MediaQuery.of(context).size.height * .10, ), SizedBox( height: 20, ), Text( 'There is an issue at server please try after some time', style: serverIssueTextStyle(), ), ], ) : userAddress == '' ? Column( mainAxisAlignment: MainAxisAlignment.center, children: [ /*Image( image: AssetImage('images/resourceblue.pngs'), // height: MediaQuery.of(context).size.height * .10, ),*/ Icon( Icons.location_on_outlined, color: primaryColor, size: 40, ), SizedBox( height: 20, ), Text( 'Please select location to see near by pharmacies', style: TextStyle( color: primaryColor, fontWeight: FontWeight.bold, ), ), ], ) : Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Image( image: AssetImage('images/no_data.png'), // height: MediaQuery.of(context).size.height * .10, ), SizedBox( height: 20, ), Text( 'No Pharmacies', style: serverIssueTextStyle(), ), ], ), )); } } Widget _allPrescriptions(){ if (prescriptionsList.length != 0) { return Column( children: [ GridView.builder( shrinkWrap: true, physics: NeverScrollableScrollPhysics(), itemCount: FilteredList.length, itemBuilder: (context, index) { return Card( elevation: 2.0, child: CheckboxListTile( title: Padding( padding: EdgeInsets.fromLTRB(10, 10, 0, 0), child: Row( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: [ Container( width: MediaQuery.of(context).size.width * .18, height: MediaQuery.of(context).size.height * .10, decoration: BoxDecoration( shape: BoxShape.rectangle, image: DecorationImage( image: FilteredList[index].picture == '' ? AssetImage("images/logo.png") : NetworkImage( FilteredList[index].picture) as ImageProvider, // picked file fit: BoxFit.contain)), ), SizedBox( width: 5, ), Expanded( child: Container( width: MediaQuery.of(context).size.width * .70, child: Column( mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( FilteredList[index] .pharmacy_name .toUpperCase(), style: wrapTextStyleBlack()), SizedBox( height: 10, ), Text( FilteredList[index] .contact_number .toUpperCase(), style: wrapTextStyleBlack()), /*Visibility( visible: FilteredList[index].supplier_alternate_phone_number!='', child: Text( FilteredList[index] .supplier_alternate_phone_number .toUpperCase(), style: wrapTextStyleBlack()),),*/ SizedBox( height: 10, ), Text( FilteredList[index] .pharmacy_address .toUpperCase(), style: wrapTextStyleBlack()), Visibility( visible: FilteredList[index].description != '', child: SizedBox( height: 10, ), ), Visibility( visible: FilteredList[index].description != '', child: Text( FilteredList[index] .description .toUpperCase(), style: wrapTextStyleBlack()), ), SizedBox( height: 10, ), /*Text( FilteredList[index] .starting_price .toUpperCase(), style: wrapTextStyleBlack()), SizedBox(height: 10,),*/ ], )), ), ], ) ), checkColor: Colors.white, activeColor: primaryColor, value: FilteredList[index].isChecked, onChanged: (val) { setState( () { FilteredList[index].isChecked = val!; }, ); if (FilteredList[index].isChecked) { pharmaciesCheckboxes.add({ 'pharmacyId': FilteredList[index] .pharmacy_id, }); } else { pharmaciesCheckboxes.removeWhere((e) => e['pharmacyId'] .toString() .toUpperCase() == FilteredList[index] .pharmacy_id .toString() .toUpperCase()); } }, ), ); }, gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 1,//.size.width * .33, childAspectRatio: MediaQuery.of(context).size.width / (MediaQuery.of(context).size.height /7)), ), ElevatedButton( style: ElevatedButton.styleFrom( primary: primaryColor, // background onPrimary: Colors.white, // foreground ), onPressed: () async { if(Url!=''&&pharmaciesCheckboxes.isNotEmpty){ AppSettings.preLoaderDialog(context); var payload = new Map(); payload["picture"] = Url.toString(); payload["pharmacies"] = pharmaciesCheckboxes; bool status = await AppSettings.uploadPrescription(payload); try { if (status) { Navigator.of(context, rootNavigator: true).pop(); Url=''; pharmaciesCheckboxes = []; AppSettings.longSuccessToast( "Prescription uploaded Successfully"); // Navigator.pop(context); getAllPharmaciesData(dropdownArea); /* Navigator.push( context, MaterialPageRoute( builder: (context) => ConnectionsView()), );*/ } else { Navigator.of(context, rootNavigator: true).pop(); AppSettings.longFailedToast( "Failed to upload prescription"); } } catch (exception) { AppSettings.longFailedToast("Failed to upload prescription"); print(exception); } } else{ AppSettings.longFailedToast('Please select image and pharmacies' ); } }, child: const Text('Upload'), ) ], ); } else { return Center( child: Padding( padding: EdgeInsets.fromLTRB(0, 40, 0, 0), child: isSereverIssue ? Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Image( image: AssetImage('images/serverissue.png'), // height: MediaQuery.of(context).size.height * .10, ), SizedBox( height: 20, ), Text( 'There is an issue at server please try after some time', style: serverIssueTextStyle(), ), ], ) : userAddress == '' ? Column( mainAxisAlignment: MainAxisAlignment.center, children: [ /*Image( image: AssetImage('images/resourceblue.pngs'), // height: MediaQuery.of(context).size.height * .10, ),*/ Icon( Icons.location_on_outlined, color: primaryColor, size: 40, ), SizedBox( height: 20, ), Text( 'Please select location to see near by pharmacies', style: TextStyle( color: primaryColor, fontWeight: FontWeight.bold, ), ), ], ) : Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Image( image: AssetImage('images/no_data.png'), // height: MediaQuery.of(context).size.height * .10, ), SizedBox( height: 20, ), Text( 'No Pharmacies', style: serverIssueTextStyle(), ), ], ), )); }} /**/ @override Widget build(BuildContext context) { return Scaffold( appBar: AppSettings.appBar('Prescriptions'), body: Container( child: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.start, children: [ Padding( padding: EdgeInsets.all(10), child: ElevatedButton( style: ElevatedButton.styleFrom( primary: primaryColor, // background onPrimary: Colors.white, // foreground ), onPressed: () async { Navigator.push( context, MaterialPageRoute( builder: (context) => const AddPrescription()), ); }, child: const Text('Add'), ), ), _allPrescriptions(), ], )), ); } }