import 'dart:io'; import 'package:flutter/material.dart'; import 'dart:convert'; import 'package:flutter/services.dart'; import 'package:http/http.dart' as http; import 'package:fluttertoast/fluttertoast.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:intl/intl.dart'; import 'package:flutter_styled_toast/flutter_styled_toast.dart'; import 'dart:async'; import 'package:geolocator/geolocator.dart'; import 'package:watermanagement/preloader.dart'; const Color primaryColor = Color(0XFF0D4E84); const Color greyColor = Color(0XFF8F8E8E); const Color textFieldStartColor = Colors.grey; const Color screenBackgroundColor = Color(0XFFEAF6FF); const Color screenBackgroundColord = Colors.black12; const Color dashboardbackground = Color(0XFFF5F5F5); Color AppBarGradient_1 = Color(0XFF1258F6); TextStyle PreloaderText() { return TextStyle(color: Colors.blueAccent); } TextStyle labelTextStyle() { return TextStyle(color: primaryColor, fontSize: 12); } TextStyle textButtonStyle() { return TextStyle(color: primaryColor,fontSize: 15); } TextStyle iconBelowTextStyle() { return TextStyle(fontSize: 10,color: primaryColor); } TextStyle valuesTextStyle() { return TextStyle(fontSize: 12,fontWeight: FontWeight.bold,); } Text capacitySuffixText(){ return Text('in Ltrs.'); } TextStyle dashboardTextStyle() { return TextStyle(color: primaryColor, fontSize: 12,fontWeight: FontWeight.bold,); } TextStyle labelTextStyleBold() { return TextStyle(color: primaryColor, fontWeight: FontWeight.bold,); } TextStyle serverIssueTextStyle() { return TextStyle(color: Colors.red, fontSize: 15); } class AppSettings { static SharedPreferences sharedPreferences = SharedPreferences.getInstance() as SharedPreferences; static String suppliername = ''; static String email = ''; static String phoneNumber = ''; static String accessToken = ''; static String customerId = ''; static String supplierId = ''; static String customerIdsign = ''; static List storedPreferenceValidKeys = ['suppliername', 'access_token']; static String preloadText = 'Please wait'; static String latitude=''; static String longitude=''; static String supplierAddress = ''; static bool servicestatus = false; static bool haspermission = false; static late LocationPermission permission; static late Position position; static String long = "", lat = ""; late StreamSubscription positionStream; //api urls static String host = 'http://35.207.198.4:3000/api/'; static String loginUrl = host+'supplierlogin'; static String signUpUrl = host+'suppliers'; static String verifyPhnUrl = host+'supplierphone'; static String resetTokenUrl = host+'reset_token'; static String updateProfileUrl = host + 'update/currentSupplier'; static String addTankerUrl = host + 'addTankers'; static String getTankersDataUrl = host + 'getTankers'; static String deleteTankerUrl = host + 'deleteTanker'; static String UpdateTankerUrl = host + 'updateTankers'; static String addDeliveryboyUrl = host + 'addDeliveryboys'; static String getAllDeliverboyUrl = host + 'getActiveDeliveryboys'; static String updateDeliveryboyUrl = host + 'updatedeliveryboy'; static String deleteDeliveryboyUrl = host + 'deletedeliveryboy'; static String pendingCustomersUrl = host + 'pendingCustomers'; static String connectedCustomersUrl = host + 'connectedCustomers'; String a=""; String b=""; static String acceptRequestUrl = host +"friend-request/"+ supplierId+"/accept"; static File? updatedImage; static String image=''; static var api = { 'signIn': host + '/login', }; /*Formatter*/ static String formNum(String s) { var comma = NumberFormat('##,##,##,###'); return comma.format( int.parse(s), ); } /* Preloader */ static GlobalKey preLoaderKey = new GlobalKey(); static Future preLoaderDialog(BuildContext context) async { try { preLoaderKey = new GlobalKey(); Dialogs.showLoadingDialog(context, preLoaderKey); } catch (error) {} } ////request headers with content type static Future> buildRequestHeaders() async { Map _headers = new Map(); _headers[HttpHeaders.contentTypeHeader] = 'application/json'; _headers['Authorization'] = accessToken; return _headers; } //request headers without content type static Future> buildPutRequestHeaders() async { Map _headers = new Map(); _headers['Authorization'] = accessToken; return _headers; } static Future> buildPutRequestHeadersForResetToken() async { Map _headers = new Map(); return _headers; } // Shared preferences save,get and clear data static saveData(String _key, _value, type) async { sharedPreferences = await SharedPreferences.getInstance(); if (type == 'STRING') { await sharedPreferences.setString(_key, _value.toString()); } else if (type == 'INTEGER') { await sharedPreferences.setInt(_key, _value); } else if (type == 'BOOL') { await sharedPreferences.setBool(_key, _value); } else if (type == 'DOUBLE') { await sharedPreferences.setDouble(_key, _value); } } static getData(String _key, type) async { sharedPreferences = await SharedPreferences.getInstance(); if (type == 'STRING') { return sharedPreferences.getString(_key) ?? ''; } else if (type == 'INTEGER') { return sharedPreferences.getInt(_key) ?? -1; } else if (type == 'BOOL') { return sharedPreferences.getBool(_key) ?? -1; } else if (type == 'DOUBLE') { return sharedPreferences.getDouble(_key) ?? -1; } } static clearSharedPreferences() async { sharedPreferences = await SharedPreferences.getInstance(); await sharedPreferences.clear(); } /*Sign in check*/ static Future isSigIn() async { bool isSignInCheck = true; for (var eachKey in storedPreferenceValidKeys) { if (await getData(eachKey, 'STRING') == '') { isSignInCheck = false; } } return isSignInCheck; } static Future internetConnectivity() async { try { final result = await InternetAddress.lookup('google.com'); if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) { return true; } } on SocketException catch (_) { return false; } return false; } /*Apis Starts here*/ static Future login(payload) async { var response = await http.post(Uri.parse(loginUrl), body: json.encode(payload), headers: {'Content-type': 'application/json'}); if (response.statusCode == 200) { try { var _response = json.decode(response.body); print(_response['simplydata']['error']); if (_response['simplydata']['error'] == false) { await saveAvailableReportAndLocationsInMemory(_response); return true; } else { return false; } } catch (e) { // display error toast return false; } } else { return false; } } static Future signUp(payload) async { var response = await http.post(Uri.parse(signUpUrl), body: json.encode(payload), headers: {'Content-type': 'application/json'}); if (response.statusCode == 200) { try { var _response = json.decode(response.body); // customerIdsign =_response['armintatankdata']['supplierId']; print(_response); return true; } catch (e) { // display error toast return false; } } else { return false; } } static Future verifyPhn(payload) async { var response = await http.post(Uri.parse(verifyPhnUrl), body: json.encode(payload), headers: {'Content-type': 'application/json'}); if (response.statusCode == 200) { try { var _response = json.decode(response.body); print(_response); if (_response['armintatankdata']['error'] == false) { return true; } else { return false; } } catch (e) { // display error toast return false; } } else { return false; } } static Future resetToken() async { var uri = Uri.parse(resetTokenUrl+ '/' + customerId); try { // var response = await http.get(uri, headers: await buildPutRequestHeaders()); var response = await http.get(uri, headers: await buildPutRequestHeadersForResetToken()); if (response.statusCode == 200) { print(response.body); var res=jsonDecode(response.body); print(res); accessToken=res['access_token']; return true; } else { return false; } } catch (e) { print(e); return false; } } static Future updateProfile(payload) async { try { var response = await http.put( Uri.parse(updateProfileUrl + '/' + supplierId), body: json.encode(payload), headers: await buildRequestHeaders()); if (response.statusCode == 200) { var _response = json.decode(response.body); suppliername = _response['suppliername']; phoneNumber = _response['phone']; email = _response['emails'][0]['email']; return true; } else { return false; } } catch (e) { print(e); return false; } } static Future addTankers(payload) async { var response = await http.post(Uri.parse(addTankerUrl + '/' + supplierId), body: json.encode(payload), headers: await buildRequestHeaders()); if (response.statusCode == 200) { try { var _response = json.decode(response.body); print(_response); return true; } catch (e) { // display error toast return false; } } else if (response.statusCode == 401) { bool status = await AppSettings.resetToken(); if (status) { response = await http.post(Uri.parse(addTankerUrl + '/' + supplierId), body: json.encode(payload), headers: await buildRequestHeaders()); if (response.statusCode == 200) { return true; } else { return false; } } else { return false; } } else { return false; } } static Future getTankers() async { var uri = Uri.parse(getTankersDataUrl); uri = uri.replace(query: 'supplierId=$supplierId'); var response = await http.get(uri, headers: await buildRequestHeaders()); if (response.statusCode == 200) { return response.body; } else if (response.statusCode == 401) { bool status = await AppSettings.resetToken(); if (status) { response = await http.get(uri, headers: await buildRequestHeaders()); if (response.statusCode == 200) { return response.body; } else { return ''; } } else { return ''; } } else { return ''; } } static Future updateTanker(tankerName, payload) async { var uri = Uri.parse(UpdateTankerUrl + '/' + supplierId); uri = uri.replace(query: 'tankerName=$tankerName'); try { var response = await http.put(uri, body: json.encode(payload), headers: await buildRequestHeaders()); if (response.statusCode == 200) { return true; } else if (response.statusCode == 401) { bool status = await AppSettings.resetToken(); if (status) { response = await http.put(uri, body: json.encode(payload), headers: await buildRequestHeaders()); if (response.statusCode == 200) { return true; } else { return false; } } else { return false; } } else { return false; } } catch (e) { print(e); return false; } } static Future deleteTanker(tankerName) async { var uri = Uri.parse(deleteTankerUrl + '/' + supplierId); uri = uri.replace(query: 'tankerName=$tankerName'); try { var response = await http.put(uri, headers: await buildPutRequestHeaders()); if (response.statusCode == 200) { return true; } else if (response.statusCode == 401) { bool status = await AppSettings.resetToken(); if (status) { response = await http.put(uri, headers: await buildPutRequestHeaders()); if (response.statusCode == 200) { return true; } else { return false; } } else { return false; } } else { return false; } } catch (e) { print(e); return false; } } static Future addDeliverboy(payload) async { var response = await http.post(Uri.parse(addDeliveryboyUrl + '/' + supplierId), body: json.encode(payload), headers: await buildRequestHeaders()); if (response.statusCode == 200) { try { var _response = json.decode(response.body); print(_response); return true; } catch (e) { // display error toast return false; } } else if (response.statusCode == 401) { bool status = await AppSettings.resetToken(); if (status) { response = await http.post(Uri.parse(addDeliveryboyUrl + '/' + supplierId), body: json.encode(payload), headers: await buildRequestHeaders()); if (response.statusCode == 200) { return true; } else { return false; } } else { return false; } } else { return false; } } static Future getAllDeliverboy() async { var response = await http.get(Uri.parse(getAllDeliverboyUrl + '/' + supplierId), headers: await buildRequestHeaders()); if (response.statusCode == 200) { try { var _response = json.decode(response.body); print(_response); return response.body; } catch (e) { // display error toast return ''; } } else if (response.statusCode == 401) { bool status = await AppSettings.resetToken(); if (status) { response = await http.get(Uri.parse(getAllDeliverboyUrl + '/' + supplierId), headers: await buildRequestHeaders()); if (response.statusCode == 200) { return response.body; } else { return ""; } } else { return ""; } } else { return ""; } } static Future updateDeliveryboy(phone, payload) async { var uri = Uri.parse(updateDeliveryboyUrl + '/' + supplierId); uri = uri.replace(query: 'phone=$phone'); try { var response = await http.put(uri, body: json.encode(payload), headers: await buildRequestHeaders()); if (response.statusCode == 200) { return true; } else if (response.statusCode == 401) { bool status = await AppSettings.resetToken(); if (status) { response = await http.put(uri, body: json.encode(payload), headers: await buildRequestHeaders()); if (response.statusCode == 200) { return true; } else { return false; } } else { return false; } } else { return false; } } catch (e) { print(e); return false; } } static Future deleteDeliveryboy(phone) async { var uri = Uri.parse(deleteDeliveryboyUrl + '/' + supplierId); uri = uri.replace(query: 'phone=$phone'); try { var response = await http.put(uri, headers: await buildPutRequestHeaders()); if (response.statusCode == 200) { return true; } else if (response.statusCode == 401) { bool status = await AppSettings.resetToken(); if (status) { response = await http.put(uri, headers: await buildPutRequestHeaders()); if (response.statusCode == 200) { return true; } else { return false; } } else { return false; } } else { return false; } } catch (e) { print(e); return false; } } static Future getPendingSuppliers() async { var response = await http.get(Uri.parse(pendingCustomersUrl + '/' + supplierId), headers: await buildRequestHeaders()); if (response.statusCode == 200) { try { var _response = json.decode(response.body); print(_response); return response.body; } catch (e) { // display error toast return ''; } } else if (response.statusCode == 401) { bool status = await AppSettings.resetToken(); if (status) { response = await http.get(Uri.parse(pendingCustomersUrl + '/' + supplierId), headers: await buildRequestHeaders()); if (response.statusCode == 200) { return response.body; } else { return ""; } } else { return ""; } } else { return ""; } } static Future getConnectedCustomers() async { var response = await http.get(Uri.parse(connectedCustomersUrl + '/' + supplierId), headers: await buildRequestHeaders()); if (response.statusCode == 200) { try { var _response = json.decode(response.body); print(_response); return response.body; } catch (e) { // display error toast return ''; } } else if (response.statusCode == 401) { bool status = await AppSettings.resetToken(); if (status) { response = await http.get(Uri.parse(connectedCustomersUrl + '/' + supplierId), headers: await buildRequestHeaders()); if (response.statusCode == 200) { return response.body; } else { return ""; } } else { return ""; } } else { return ""; } } static Future acceptRequest( payload) async { var uri = Uri.parse(acceptRequestUrl ); try { var response = await http.post(uri, body: json.encode(payload), headers: await buildRequestHeaders()); if (response.statusCode == 200) { return true; } else if (response.statusCode == 401) { bool status = await AppSettings.resetToken(); if (status) { response = await http.put(uri, body: json.encode(payload), headers: await buildRequestHeaders()); if (response.statusCode == 200) { return true; } else { return false; } } else { return false; } } else { return false; } } catch (e) { print(e); return false; } } /*Apis ends here*/ //save data local static Future saveAvailableReportAndLocationsInMemory(dynamic input) async { // save login name information await saveData('suppliername', input['simplydata']['suppliername'], 'STRING'); await saveData('access_token', input['simplydata']['access_token'], 'STRING'); await saveData('phone', input['simplydata']['phone'], 'STRING'); await saveData('email', input['simplydata']['email'][0]['email'], 'STRING'); await saveData('supplierId', input['simplydata']['supplierId'], 'STRING'); await saveData('supplieraddress', input['simplydata']['office_address'], 'STRING'); await loadDataFromMemory(); } static Future saveProfile(dynamic image) async { // save login name information await saveData('profile', image.toString(), 'STRING'); //await loadDataFromMemory(); } static Future loadDataFromMemory() async { suppliername = await getData('suppliername', 'STRING'); accessToken = await getData('access_token', 'STRING'); email=await getData('email', 'STRING'); phoneNumber=await getData('phone', 'STRING'); supplierId=await getData('supplierId', 'STRING'); supplierAddress=await getData('supplieraddress', 'STRING'); } //assign saved values to variables static Future getProfile() async { final image1 = await getData('profile', 'STRING'); //Io.File.fromUri(imageFile.uri) if (image1 == null) return; if(image1==''){ updatedImage=null; } else{ final imageTemp =File(image1); updatedImage=imageTemp; } print(updatedImage); } static Widget noDataUI(String _tabName) { _tabName = _tabName ?? ''; return Container( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Image( image: AssetImage('images/no_data.png'), width: 200, ), SizedBox( height: 8, ), Text( 'There is no data to show you right now.', style: TextStyle( fontSize: 12, color: Colors.grey[600], fontFamily: 'Swis2', ), ), SizedBox( height: 5, ), Text( _tabName, style: TextStyle(fontSize: 15, fontFamily: 'Swis1'), ), ], ), ); } static appBar(String title) { title = title ?? ''; return AppBar( backgroundColor: primaryColor, title: Text(title), ); } static void longFailedToast(String message) { Fluttertoast.showToast( msg: message, toastLength: Toast.LENGTH_LONG, gravity: ToastGravity.BOTTOM, timeInSecForIosWeb: 1, backgroundColor: Colors.red, textColor: Colors.white, fontSize: 16.0); } static void longFailedStyledToast(String message,context) { showToast(message, context: context, animation: StyledToastAnimation.scale, reverseAnimation: StyledToastAnimation.fade, position: StyledToastPosition.bottom, animDuration: Duration(seconds: 1), duration: Duration(seconds: 6), curve: Curves.elasticOut, reverseCurve: Curves.linear, backgroundColor: Colors.red, ); } static void longSuccessToast(String message) { Fluttertoast.showToast( msg: message, toastLength: Toast.LENGTH_SHORT, gravity: ToastGravity.BOTTOM, timeInSecForIosWeb: 1, backgroundColor: Colors.green, textColor: Colors.white, fontSize: 16.0 ); } /*location*/ static checkGps() async { servicestatus = await Geolocator.isLocationServiceEnabled(); if(servicestatus){ permission = await Geolocator.checkPermission(); if (permission == LocationPermission.denied) { permission = await Geolocator.requestPermission(); if (permission == LocationPermission.denied) { print('Location permissions are denied'); }else if(permission == LocationPermission.deniedForever){ print("'Location permissions are permanently denied"); }else{ haspermission = true; } }else{ haspermission = true; } if(haspermission){ /*setState(() { //refresh the UI });*/ await getLocation(); } } else{ print("GPS Service is not enabled, turn on GPS location"); } } static getLocation() async { position = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high); /*print(position.longitude); //Output: 80.24599079 print(position.latitude);*/ //Output: 29.6593457 long = await position.longitude.toString(); lat = await position.latitude.toString(); /*setState(() { //refresh UI });*/ LocationSettings locationSettings = LocationSettings( accuracy: LocationAccuracy.high, //accuracy of the location data distanceFilter: 100, //minimum distance (measured in meters) a //device must move horizontally before an update event is generated; ); StreamSubscription positionStream = Geolocator.getPositionStream( locationSettings: locationSettings).listen((Position position) { print(position.longitude); //Output: 80.24599079 print(position.latitude); //Output: 29.6593457 long = position.longitude.toString(); lat = position.latitude.toString(); /*setState(() { //refresh UI on update });*/ }); } }