You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
healthcare-frontend/lib/prescriptions/oreder_medicines.dart

718 lines
30 KiB

import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:healthcare_user/common/settings.dart';
import 'package:healthcare_user/google_maps_place_picker_mb/src/models/pick_result.dart';
import 'package:healthcare_user/google_maps_place_picker_mb/src/place_picker.dart';
import 'package:healthcare_user/keys.dart';
import 'package:healthcare_user/models/pharmacies_model.dart';
import 'package:google_maps_flutter_android/google_maps_flutter_android.dart';
import 'package:google_maps_flutter_platform_interface/google_maps_flutter_platform_interface.dart';
import 'package:location/location.dart' as locationmap;
class OrderMedicines extends StatefulWidget {
var prescriptionDetails;
OrderMedicines({this.prescriptionDetails});
@override
State<OrderMedicines> createState() => _OrderMedicinesState();
}
class _OrderMedicinesState extends State<OrderMedicines> {
double lat = 0;
double lng = 0;
String userAddress = '';
String dropdownArea = '2';
//String dropdownType = 'Tank';
var AreaItems = ['2', '5', '10', '25', '50', '100'];
List pharmaciesCheckboxes = [];
List selectedPharmacies = [];
bool isLoading = false;
bool isSereverIssue = false;
List<PharmaciesModel> pharmaciesList = [];
List<PharmaciesModel> FilteredList = [];
PickResult? selectedPlace;
bool _mapsInitialized = false;
final String _mapsRenderer = "latest";
var kInitialPosition = const LatLng(15.462477, 78.717401);
locationmap.Location location = locationmap.Location();
final GoogleMapsFlutterPlatform mapsImplementation =
GoogleMapsFlutterPlatform.instance;
void initRenderer() {
if (_mapsInitialized) return;
if (mapsImplementation is GoogleMapsFlutterAndroid) {
switch (_mapsRenderer) {
case "legacy":
(mapsImplementation as GoogleMapsFlutterAndroid)
.initializeWithRenderer(AndroidMapRenderer.legacy);
break;
case "latest":
(mapsImplementation as GoogleMapsFlutterAndroid)
.initializeWithRenderer(AndroidMapRenderer.latest);
break;
}
}
setState(() {
_mapsInitialized = true;
});
}
Future<void> getAllPharmaciesData(var distance) async {
isLoading = 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);
}
});
isLoading = false;
});
} catch (e) {
setState(() {
isLoading = false;
isSereverIssue = true;
});
}
}
showListOfSelectedPharmacies() async {
return showDialog(
context: context,
barrierDismissible: false,
builder: (BuildContext context) {
return StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Container(
height: 300.0, // Change as per your requirement
width: 300.0, // Change as per your requirement
child: ListView.builder(
shrinkWrap: true,
itemCount: 5,
itemBuilder: (BuildContext context, int index) {
return ListTile(
title: Text('Gujarat, India'),
);
},
),
);
/* return AlertDialog(
title: const Text('Selected pharmacies'),
content: SingleChildScrollView(
child: Expanded(
child: ListView.builder(
itemCount: selectedPharmacies.length,
itemBuilder: (context, index) {
return Card(
child: Column(
children: [
Text(selectedPharmacies[index].pharmacy_name)
],
),
);},
),
)
),
actions: <Widget>[
TextButton(
child: Text('Cancel', style: textButtonStyle()),
onPressed: () {
Navigator.of(context).pop();
},
),
TextButton(
child: Text('Get quote', style: textButtonStyle()),
onPressed: () async {
Navigator.of(context).pop();
},
),
],
);*/
});
},
);
}
Widget setupAlertDialoadContainer() {
return Container(
height: 300.0, // Change as per your requirement
width: 300.0, // Change as per your requirement
child: ListView.builder(
shrinkWrap: true,
itemCount: 5,
itemBuilder: (BuildContext context, int index) {
return ListTile(
title: Text('Gujarat, India'),
);
},
),
);
}
Widget _pharamciesData() {
if (FilteredList.length != 0) {
return
Container(
color: secondaryColor,
child: Column(crossAxisAlignment: CrossAxisAlignment.end, children: [
Expanded(
child: GridView.builder(
itemCount: FilteredList.length,
itemBuilder: (context, index) {
return Card(
elevation: 2.0,
child: CheckboxListTile(
title: Padding(
padding: EdgeInsets.fromLTRB(0, 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()),
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,
),
],
)),
),
],
)),
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,
});
selectedPharmacies.add(FilteredList[index]);
} else {
pharmaciesCheckboxes.removeWhere((e) =>
e['pharmacyId'].toString().toUpperCase() ==
FilteredList[index]
.pharmacy_id
.toString()
.toUpperCase());
selectedPharmacies.remove(FilteredList[index]);
}
},
),
);
},
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 1, //.size.width * .33,
childAspectRatio: MediaQuery.of(context).size.width /
(MediaQuery.of(context).size.height / 7)),
),
),
Padding(
padding: EdgeInsets.all(0),
child: Container(
width: double.infinity,
height: MediaQuery.of(context).size.height * .06,
child: ElevatedButton(
style: ElevatedButton.styleFrom(
primary: buttonColors, // background
onPrimary: Colors.black, // foreground
),
onPressed: () async {
if(pharmaciesCheckboxes.length==3){
var payload = new Map<String, dynamic>();
payload["picture"] = widget.prescriptionDetails.prescription_url.toString();
payload["pharmacies"] = pharmaciesCheckboxes;
payload["familyDetails"] = {
"patient_name": widget.prescriptionDetails.patient_name.toString(),
"patient_age": int.parse(widget.prescriptionDetails.age.toString()),
"patient_gender": widget.prescriptionDetails.gender,
"patient_address": userAddress
};
bool status = await AppSettings.getQuotation(payload);
if(status){
AppSettings.longSuccessToast('Quotation request sent successfully');
}
else{
AppSettings.longFailedToast('Get quotation failed try after some time');
}
}
else if(pharmaciesCheckboxes.length>3){
showListOfSelectedPharmacies();
}
else{
AppSettings.longFailedToast('Please select at least three pharmacies to get quotation');
}
},
child: Text('Get quote'),
)),
),
]),
);
}
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 tankers',style:TextStyle(
color: primaryColor,
fontWeight: FontWeight.bold,
),),
],
):
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
/*Image(
image: AssetImage('images/resourceblue.pngs'),
// height: MediaQuery.of(context).size.height * .10,
),*/
Icon(
Icons.info,
color: primaryColor,
size: 40,
),
SizedBox(
height: 20,
),
Text(
'No pharmacies near to your selected locaton',
style: TextStyle(
color: primaryColor,
fontWeight: FontWeight.bold,
),
),
],
)
));
}
}
@override
void initState() {
lat = AppSettings.userLatitude;
lng = AppSettings.userLongitude;
userAddress = AppSettings.userAddress;
getAllPharmaciesData(dropdownArea);
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppSettings.appBar('Order Medicines'),
body: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.start,
children: [
Padding(
padding: EdgeInsets.all(10),
child: Row(
children: [
Container(
width: MediaQuery.of(context).size.width * .18,
height: MediaQuery.of(context).size.height * .10,
decoration: BoxDecoration(
shape: BoxShape.rectangle,
image: DecorationImage(
image: NetworkImage(widget.prescriptionDetails.prescription_url)
as ImageProvider, // picked file
fit: BoxFit.contain)),
),
SizedBox(
width: MediaQuery.of(context).size.width * .02,
),
Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
widget.prescriptionDetails.prescription_name
.toString()
.toUpperCase(),
style: valuesTextStyle()),
Text(
widget.prescriptionDetails.patient_name
.toString()
.toUpperCase(),
style: valuesTextStyle()),
Text(
widget.prescriptionDetails.gender
.toString()
.toUpperCase(),
style: valuesTextStyle()),
Text(
widget.prescriptionDetails.age
.toString()
.toUpperCase(),
style: valuesTextStyle()),
],
),
),
],
)),
Padding(
padding: EdgeInsets.all(10),
child: TextButton(
onPressed: () {},
child: const Text(
'Want to order non prescribed items?',
style: TextStyle(
fontSize: 15,
decoration: TextDecoration.underline,
color: primaryColor),
)),
),
Padding(
padding: EdgeInsets.all(10),
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Your address',
style: labelTextStyle(),
),
Text(
userAddress,
style: valuesTextStyle(),
),
Row(
children: [
TextButton(
child: const Text(
'Change',
style: TextStyle(
fontSize: 15,
decoration: TextDecoration.underline,
color: primaryColor),
),
onPressed: () {
location.serviceEnabled().then((value) {
if (value) {
initRenderer();
Navigator.push(
context,
MaterialPageRoute(
builder: (context) {
return PlacePicker(
resizeToAvoidBottomInset: false,
hintText: "Find a place ...",
searchingText: "Please wait ...",
selectText: "Select place",
outsideOfPickAreaText:
"Place not in area",
initialPosition: kInitialPosition,
useCurrentLocation: true,
selectInitialPosition: true,
usePinPointingSearch: true,
usePlaceDetailSearch: true,
zoomGesturesEnabled: true,
zoomControlsEnabled: true,
onMapCreated: (GoogleMapController
controller) {},
onPlacePicked: (PickResult result) {
setState(() {
selectedPlace = result;
lat = selectedPlace!
.geometry!.location.lat;
lng = selectedPlace!
.geometry!.location.lng;
if (selectedPlace!
.types!.length ==
1) {
userAddress = selectedPlace!
.formattedAddress!;
} else {
userAddress = selectedPlace!
.name! +
', ' +
selectedPlace!
.formattedAddress!;
}
Navigator.of(context).pop();
getAllPharmaciesData(
dropdownArea);
});
},
onMapTypeChanged:
(MapType mapType) {},
apiKey: Platform.isAndroid
? APIKeys.androidApiKey
: APIKeys.iosApiKey,
forceAndroidLocationManager: true,
);
},
),
);
} else {
showGeneralDialog(
context: context,
pageBuilder: (context, x, y) {
return Scaffold(
backgroundColor:
Colors.grey.withOpacity(.5),
body: Center(
child: Container(
width: double.infinity,
height: 150,
padding:
const EdgeInsets.symmetric(
horizontal: 20),
child: Card(
child: Padding(
padding: const EdgeInsets.all(
10.0),
child: Column(
mainAxisAlignment:
MainAxisAlignment
.center,
children: [
const Text(
"Please enable the location",
style: TextStyle(
fontSize: 18,
fontWeight:
FontWeight.w500,
),
),
const SizedBox(
height: 20,
),
ElevatedButton(
onPressed: () {
Navigator.pop(
context);
},
child: const Text(
"Cancel"),
),
],
),
),
),
),
),
);
},
);
}
});
},
),
Icon(
Icons.location_on_outlined,
color: primaryColor,
size: 20,
),
],
)
],
),
),
Expanded(
child: Container(
height: MediaQuery.of(context).size.height * .09,
padding: const EdgeInsets.fromLTRB(10, 10, 0, 0),
child: DropdownButtonFormField(
value: dropdownArea,
isExpanded: true,
decoration: const InputDecoration(
prefixIcon: Icon(
Icons.area_chart,
color: primaryColor,
),
border: OutlineInputBorder(
borderSide: BorderSide(color: greyColor)),
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(color: greyColor),
),
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(color: greyColor),
),
labelText: 'distance',
labelStyle: TextStyle(
color: greyColor, //<-- SEE HERE
),
),
hint: Text('Select Area'),
// Down Arrow Icon
icon: const Icon(Icons.keyboard_arrow_down),
// Array list of items
items: AreaItems.map((String items) {
return DropdownMenuItem(
value: items,
child: Text(items),
);
}).toList(),
// After selecting the desired option,it will
// change button value to selected value
onChanged: (String? newValue) {
setState(() {
dropdownArea = newValue!;
});
getAllPharmaciesData(dropdownArea);
},
),
),
)
],
),
),
Expanded(
child: isLoading
? Center(
child: CircularProgressIndicator(
color: primaryColor,
strokeWidth: 5.0,
),
)
: _pharamciesData(),
)
],
));
}
}