apiservices.dart 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. // ignore_for_file: unnecessary_question_mark, non_constant_identifier_names, unused_local_variable, prefer_interpolation_to_compose_strings, use_build_context_synchronously
  2. import 'dart:io';
  3. import 'dart:convert';
  4. import 'package:fluttertoast/fluttertoast.dart';
  5. import 'package:general_package/get_device_info/get_device_info.dart';
  6. import 'package:general_package/mainUrl_provider/mainUrl_provider.dart';
  7. import 'package:geolocator/geolocator.dart';
  8. import 'package:get/get.dart';
  9. import 'package:provider/provider.dart';
  10. // import 'package:toast/toast.dart';
  11. import 'package:flutter/material.dart';
  12. import 'package:http/http.dart' as http;
  13. import 'package:connectivity_plus/connectivity_plus.dart';
  14. import 'package:flutter/foundation.dart';
  15. import 'dart:developer' as logDev;
  16. import 'package:intl/intl.dart';
  17. import '../authservices/auth_service.dart';
  18. class APIService {
  19. BuildContext context;
  20. APIService(this.context);
  21. Future<bool> GetConnect() async {
  22. var connectivityResult = await (Connectivity().checkConnectivity());
  23. bool isInternetOn = false;
  24. if (connectivityResult == ConnectivityResult.none) {
  25. isInternetOn = false;
  26. } else if (connectivityResult == ConnectivityResult.mobile) {
  27. isInternetOn = true;
  28. } else if (connectivityResult == ConnectivityResult.wifi) {
  29. isInternetOn = true;
  30. }
  31. return isInternetOn;
  32. }
  33. getMainURL() {
  34. String mainURL =
  35. Provider.of<mainURLChangeNotifier>(context, listen: false).mainURL;
  36. return mainURL;
  37. }
  38. Future<Position?> determinePosition() async {
  39. bool serviceEnabled;
  40. LocationPermission permission;
  41. permission = await Geolocator.checkPermission();
  42. if (permission == LocationPermission.denied) {
  43. permission = await Geolocator.requestPermission();
  44. if (permission == LocationPermission.denied) {
  45. // Permissions are denied, next time you could try
  46. // requesting permissions again (this is also where
  47. // Android's shouldShowRequestPermissionRationale
  48. // returned true. According to Android guidelines
  49. // your App should show an explanatory UI now.
  50. Future.error('Location permissions are denied');
  51. }
  52. }
  53. if (permission == LocationPermission.deniedForever) {
  54. // Permissions are denied forever, handle appropriately.
  55. Future.error(
  56. 'Location permissions are permanently denied, we cannot request permissions.');
  57. }
  58. // Test if location services are enabled.
  59. serviceEnabled = await Geolocator.isLocationServiceEnabled();
  60. if (!serviceEnabled) {
  61. // Location services are not enabled don't continue
  62. // accessing the position and request users of the
  63. // App to enable the location services.
  64. // return Future.error('Location services are disabled.');
  65. Position? position = await Geolocator.getLastKnownPosition();
  66. if (position != null) {
  67. return position;
  68. }
  69. Future.error('Location services are disabled.');
  70. }
  71. // When we reach here, permissions are granted and we can
  72. // continue accessing the position of the device.
  73. return await Geolocator.getCurrentPosition();
  74. }
  75. Future<dynamic?> getData(String? url) async {
  76. try {
  77. Future<bool> internetActive = GetConnect();
  78. if (await internetActive) {
  79. print("API Service Started");
  80. String mainURL =
  81. Provider.of<mainURLChangeNotifier>(context, listen: false).mainURL;
  82. var dURL = mainURL + url!;
  83. print(dURL);
  84. print("Get Device Info Started");
  85. var deviceInfo = await DeviceInfo()
  86. .getDeviceInfo(Get.currentRoute, Get.previousRoute);
  87. print("Get Device Info Ended");
  88. var header = <String, String>{
  89. 'Content-Type': 'application/json; charset=UTF-8',
  90. 'Accept': 'application/json',
  91. };
  92. header.addAll(deviceInfo);
  93. if (authService.token.isNotEmpty) {
  94. header.addAll({"Authorization": "Bearer ${authService.token}"});
  95. }
  96. print(header);
  97. final response = await http.get(Uri.parse(dURL), headers: header);
  98. if (kDebugMode) {
  99. print(response.body);
  100. // logDev.log(response.body);
  101. }
  102. if (response.statusCode == 200 || response.statusCode == 201) {
  103. dynamic res = json.decode(response.body);
  104. if (res["message"] != null) {
  105. if (res["message"].toString().isNotEmpty) {
  106. Fluttertoast.showToast(
  107. msg: res["message"],
  108. toastLength: Toast.LENGTH_LONG,
  109. gravity: ToastGravity.BOTTOM,
  110. timeInSecForIosWeb: 1,
  111. backgroundColor: Colors.green,
  112. webPosition: "center",
  113. webBgColor: "#008000",
  114. textColor: Colors.white,
  115. fontSize: 16.0);
  116. }
  117. }
  118. return res;
  119. } else {
  120. dynamic res = json.decode(response.body);
  121. if (response.statusCode == 401) {
  122. authService.logout("/homeScreenView");
  123. }
  124. if (res["message"] != null) {
  125. FToast().init(context);
  126. FToast().showToast(child: const Text("data"));
  127. Fluttertoast.showToast(
  128. msg: res["message"].toString(),
  129. toastLength: Toast.LENGTH_LONG,
  130. gravity: ToastGravity.BOTTOM,
  131. timeInSecForIosWeb: 1,
  132. backgroundColor: Colors.red,
  133. textColor: Colors.white,
  134. webPosition: "center",
  135. webBgColor: "#FF0000",
  136. fontSize: 16.0);
  137. }
  138. }
  139. print("API Service Ended");
  140. }
  141. } on SocketException catch (_) {
  142. Fluttertoast.showToast(
  143. msg: "Please check your internet",
  144. toastLength: Toast.LENGTH_LONG,
  145. gravity: ToastGravity.BOTTOM,
  146. timeInSecForIosWeb: 1,
  147. backgroundColor: Colors.red,
  148. textColor: Colors.white,
  149. webPosition: "center",
  150. webBgColor: "#FF0000",
  151. fontSize: 16.0);
  152. }
  153. return null;
  154. }
  155. Future<dynamic?> postData(
  156. String? url,
  157. Map<String, dynamic> data,
  158. ) async {
  159. try {
  160. bool internetActive = await GetConnect();
  161. if (internetActive) {
  162. print("API Service Started");
  163. String mainURL =
  164. Provider.of<mainURLChangeNotifier>(context, listen: false).mainURL;
  165. var dURL = mainURL + url!;
  166. print(dURL);
  167. print("Get Device Info Started");
  168. var deviceInfo = await DeviceInfo()
  169. .getDeviceInfo(Get.currentRoute, Get.previousRoute);
  170. print("Get Device Info Ended");
  171. var header = <String, String>{
  172. 'Content-Type': 'application/json; charset=UTF-8',
  173. 'Accept': 'application/json',
  174. };
  175. header.addAll(deviceInfo);
  176. if (authService.token.isNotEmpty) {
  177. header.addAll({"Authorization": "Bearer ${authService.token}"});
  178. }
  179. print(header);
  180. data.forEach((key, value) {
  181. if (value.runtimeType == DateTime) {
  182. // data[key]=value.toIso8601String();
  183. data[key] = DateFormat('dd-MM-yyyy hh:mm:ss a').format(value);
  184. }
  185. });
  186. var body = json.encode(data);
  187. if (kDebugMode) {
  188. print(dURL);
  189. print(body);
  190. }
  191. final response =
  192. await http.post(Uri.parse(dURL), headers: header, body: body);
  193. if (kDebugMode) {
  194. print(response.body);
  195. // logDev.log(response.body);
  196. }
  197. if (response.body != null ||
  198. response.body.isNotEmpty ||
  199. response.body != " ") {
  200. if (response.statusCode == 200 || response.statusCode == 201) {
  201. dynamic res = json.decode(response.body);
  202. if (res["message"] != null) {
  203. if (res["message"].toString().isNotEmpty) {
  204. Fluttertoast.showToast(
  205. msg: res["message"],
  206. toastLength: Toast.LENGTH_LONG,
  207. gravity: ToastGravity.BOTTOM,
  208. timeInSecForIosWeb: 1,
  209. backgroundColor: Colors.green,
  210. textColor: Colors.white,
  211. webPosition: "center",
  212. webBgColor: "#008000",
  213. fontSize: 16.0);
  214. }
  215. }
  216. return res;
  217. } else {
  218. if (response.statusCode == 401) {
  219. authService.logout("/homeScreenView");
  220. }
  221. dynamic res = json.decode(response.body);
  222. if (res["message"] != null) {
  223. Fluttertoast.showToast(
  224. msg: res["message"].toString(),
  225. toastLength: Toast.LENGTH_LONG,
  226. gravity: ToastGravity.BOTTOM,
  227. timeInSecForIosWeb: 1,
  228. backgroundColor: Colors.red,
  229. textColor: Colors.white,
  230. webPosition: "center",
  231. webBgColor: "#FF0000",
  232. fontSize: 16.0);
  233. }
  234. }
  235. }
  236. print("API Service Ended");
  237. }
  238. } on SocketException catch (_) {
  239. Fluttertoast.showToast(
  240. msg: "Please check your internet",
  241. toastLength: Toast.LENGTH_LONG,
  242. gravity: ToastGravity.BOTTOM,
  243. timeInSecForIosWeb: 1,
  244. backgroundColor: Colors.red,
  245. textColor: Colors.white,
  246. webPosition: "center",
  247. webBgColor: "#FF0000",
  248. fontSize: 16.0);
  249. }
  250. }
  251. }