import 'dart:convert'; import 'dart:io'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:healthcare_pharmacy/dashboard.dart'; import 'package:healthcare_pharmacy/settings.dart'; import 'package:healthcare_pharmacy/zoomable_image.dart'; import 'package:intl/intl.dart'; import 'package:flutter_cupertino_datetime_picker/flutter_cupertino_datetime_picker.dart'; import 'package:image_picker/image_picker.dart'; import 'package:image/image.dart' as Img; import 'package:gallery_saver/gallery_saver.dart'; class offers extends StatefulWidget { const offers({Key? key}) : super(key: key); @override State createState() => _offersState(); } class _offersState extends State { TextEditingController offer_nameController = TextEditingController(); TextEditingController offer_codeController = TextEditingController(); TextEditingController descriptionController = TextEditingController(); TextEditingController starting_dateController = TextEditingController(); TextEditingController ending_dateController = TextEditingController(); String dropdownTypeOfCategory = 'A {1 - 500}'; var typeOfCategoryItems = [ 'A {1 - 500}', 'B {501 - 1000}', 'C {1001 - 2000}', 'D {Above 2000}', 'S {Special offer}', ]; var selIOS; final ImagePicker _picker = ImagePicker(); String offerUrl=''; File? _imageFile; Future pickImageFromGallery() async { try { final image = await _picker.pickImage(source: ImageSource.gallery); if (image == null) return; final File imageFile = File(image.path); // Read the image from file List imageBytes = await imageFile.readAsBytes(); Img.Image? decodedImage = Img.decodeImage(imageBytes); // Compress the image List compressedImage = Img.encodeJpg(decodedImage!, quality: 45); // Save the compressed image back to file await imageFile.writeAsBytes(compressedImage); AppSettings.preLoaderDialog(context); var res = await AppSettings.offeruploadImageHTTPNew(imageFile); print(jsonDecode(res)); setState(() { offerUrl = jsonDecode(res)['picture'][0]['url']; print(offerUrl); }); Navigator.of(context, rootNavigator: true).pop(); } 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 File imageFile = File(image.path); // Read the image from file List imageBytes = await imageFile.readAsBytes(); Img.Image? decodedImage = Img.decodeImage(imageBytes); // Compress the image List compressedImage = Img.encodeJpg(decodedImage!, quality: 45); // Save the original and compressed images to the gallery await GallerySaver.saveImage(image.path, albumName: 'MedicinesAlbum'); //await GallerySaver.saveImage(image.path, albumName: null); //await GallerySaver.saveImage(imageFile.path, albumName: 'YourAlbumName'); // Save the compressed image back to file await imageFile.writeAsBytes(compressedImage); AppSettings.preLoaderDialog(context); var res = await AppSettings.offeruploadImageHTTPNew(imageFile); print(jsonDecode(res)); setState(() { offerUrl = jsonDecode(res)['picture'][0]['url']; print(offerUrl); }); Navigator.of(context, rootNavigator: true).pop(); } 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 File imageFile = File(image.path); // Read the image from file List imageBytes = await imageFile.readAsBytes(); Img.Image? decodedImage = Img.decodeImage(imageBytes); // Compress the image List compressedImage = Img.encodeJpg(decodedImage!, quality: 45); await imageFile.writeAsBytes(compressedImage); AppSettings.preLoaderDialog(context); var res = await AppSettings.offeruploadImageHTTPNew(imageFile); print(jsonDecode(res)); setState(() { offerUrl = jsonDecode(res)['picture'][0]['url']; print(offerUrl); }); Navigator.of(context, rootNavigator: true).pop(); } on PlatformException catch (e) { print('Failed to pick image: $e'); } } @override Widget build(BuildContext context) { return SafeArea( child: Scaffold( appBar: AppSettings.appBar('Cteate Offers'), body: Stack(children: [ GestureDetector( onTap: () { FocusManager.instance.primaryFocus?.unfocus(); }, child: SafeArea( child: SingleChildScrollView( child: Column( children: [ SizedBox( height: 20, ), Container(child: GestureDetector( child: Container( width: MediaQuery.of(context).size.width * .60, height: MediaQuery.of(context).size.height * .15, decoration: BoxDecoration( shape: BoxShape.rectangle, border: Border.all(width: 2, color: Colors.blueGrey), image: DecorationImage( image: (offerUrl!= ''&& offerUrl!= 'null') ? NetworkImage(offerUrl) as ImageProvider : AssetImage("images/mobilebg.png"), // picked file fit: BoxFit.cover)), ), onTap: () { showModalBottomSheet( context: context, builder: (BuildContext context) { return SizedBox( height: 200, child: Center( child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ GestureDetector( child: Icon( Icons.camera_alt_outlined, size: 100, color: primaryColor, ), onTap: () async { await takeImageFromCamera(); Navigator.pop(context); }, ), SizedBox( width: MediaQuery.of(context).size.width * .20, ), GestureDetector( child: Icon( Icons.photo, size: 100, color: primaryColor, ), onTap: () async { await pickImageFromGallery(); Navigator.pop(context); }, ), ], ), ), ); }); }, ),), SizedBox( height: 15, ), GestureDetector( child: Container( child: Center( child: Text( 'Preview Image', style: TextStyle( color: primaryColor, fontSize: 20, fontWeight: FontWeight.bold, ), ), ), ), onTap: () { Navigator.push( context, MaterialPageRoute( builder: (context) => ZoomableImage(offerUrl), ), ); }, ), SizedBox( height: 20, ), Container( padding: const EdgeInsets.all(10), child: TextFormField( cursorColor: greyColor, controller: offer_nameController, textCapitalization: TextCapitalization.sentences, decoration: const InputDecoration( prefixIcon: Icon( Icons.person, color: primaryColor, ), border: OutlineInputBorder( borderSide: BorderSide(color: primaryColor)), focusedBorder: OutlineInputBorder( borderSide: BorderSide(color: primaryColor), ), enabledBorder: OutlineInputBorder( borderSide: BorderSide(color: primaryColor), ), labelText: 'Enter Offer Name', labelStyle: TextStyle( color: greyColor, //<-- SEE HERE ), ), ), ), //name SizedBox( height: 05, ), Container( padding: const EdgeInsets.all(10), child: TextFormField( cursorColor: greyColor, controller: offer_codeController, textCapitalization: TextCapitalization.sentences, decoration: const InputDecoration( prefixIcon: Icon( Icons.numbers, color: primaryColor, ), border: OutlineInputBorder( borderSide: BorderSide(color: primaryColor)), focusedBorder: OutlineInputBorder( borderSide: BorderSide(color: primaryColor), ), enabledBorder: OutlineInputBorder( borderSide: BorderSide(color: primaryColor), ), labelText: 'Enter Offer Code', labelStyle: TextStyle( color: greyColor, //<-- SEE HERE ), ), ), ), const SizedBox( height: 5, ), Container( padding: const EdgeInsets.all(10), child: TextFormField( cursorColor: greyColor, controller: descriptionController, textCapitalization: TextCapitalization.sentences, keyboardType: TextInputType.multiline, maxLines: null, decoration: const InputDecoration( prefixIcon: Icon( Icons.description, color:primaryColor, ), contentPadding: const EdgeInsets.symmetric(vertical:40.0, horizontal:30.0), border: OutlineInputBorder( borderSide: BorderSide(color: greyColor)), focusedBorder: OutlineInputBorder( borderSide: BorderSide(color: greyColor), ), enabledBorder: OutlineInputBorder( borderSide: BorderSide(color: greyColor), ), labelText: 'Enter Offer Description', labelStyle: TextStyle( color: greyColor, //<-- SEE HERE ), ), ), ), const SizedBox( height: 30, ), Container( padding: const EdgeInsets.fromLTRB(10, 10, 10, 0), child: DropdownButtonFormField( // Initial Value value: dropdownTypeOfCategory, isExpanded: true, decoration: const InputDecoration( prefixIcon: Icon( Icons.water, color: greyColor, ), border: OutlineInputBorder( borderSide: BorderSide(color: greyColor)), focusedBorder: OutlineInputBorder( borderSide: BorderSide(color: greyColor), ), enabledBorder: OutlineInputBorder( borderSide: BorderSide(color: greyColor), ), labelText: 'Select Type of Category', labelStyle: TextStyle( color: greyColor, //<-- SEE HERE ), ), hint: Text('Select Type of Category'), // Down Arrow Icon icon: const Icon(Icons.keyboard_arrow_down), // Array list of items items: typeOfCategoryItems.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(() { dropdownTypeOfCategory = newValue!; }); }, ), ), const SizedBox( height: 5, ), Container( padding: const EdgeInsets.fromLTRB(10, 10, 10, 0), child: TextFormField( readOnly: true, cursorColor: greyColor, controller: starting_dateController, decoration: InputDecoration( labelText: 'Select Start Date', prefixIcon: const Icon(Icons.date_range, color: primaryColor,), labelStyle: const TextStyle( color: greyColor, //<-- SEE HERE ), border: const OutlineInputBorder( borderSide: BorderSide(color: primaryColor)), focusedBorder: const OutlineInputBorder( borderSide: BorderSide(color: primaryColor), ), enabledBorder: const OutlineInputBorder( borderSide: BorderSide(color: primaryColor), ), suffixIcon: IconButton( icon: Icon( Icons.date_range, ), onPressed: () async { DateTime? pickedDate = await showDatePicker( context: context, /* initialDate: DateTime.now(), firstDate: DateTime(1950), lastDate: DateTime.now(),*/ initialDate: DateTime.now(), firstDate: DateTime(1950), // Set the first selectable date to a past date lastDate: DateTime(2100), // Set the last selectable date to a future date builder: (BuildContext context, Widget? child) { return Theme( data: ThemeData.dark().copyWith( colorScheme: ColorScheme.dark( primary: buttonColors, onPrimary: Colors.white, surface: buttonColors, onSurface: Colors.white, ), dialogBackgroundColor: primaryColor, ), child: child!, ); }, ); if (pickedDate != null) { print( pickedDate); //pickedDate output format => 2021-03-10 00:00:00.000 String formattedDate = DateFormat('dd-MM-yyyy').format(pickedDate); print( formattedDate); //formatted date output using intl package => 2021-03-16 setState(() { starting_dateController.text=formattedDate.toString(); }); } else {} }, ), ), ), ), const SizedBox( height: 5, ), Container( padding: const EdgeInsets.fromLTRB(10, 10, 10, 0), child: TextFormField( readOnly: true, cursorColor: greyColor, controller: ending_dateController, decoration: InputDecoration( labelText: 'Select End Date', prefixIcon: const Icon(Icons.date_range, color: primaryColor,), labelStyle: const TextStyle( color: greyColor, //<-- SEE HERE ), border: const OutlineInputBorder( borderSide: BorderSide(color: primaryColor)), focusedBorder: const OutlineInputBorder( borderSide: BorderSide(color: primaryColor), ), enabledBorder: const OutlineInputBorder( borderSide: BorderSide(color: primaryColor), ), suffixIcon: IconButton( icon: Icon( Icons.date_range, ), onPressed: () async { DateTime? pickedDate = await showDatePicker( context: context, initialDate: DateTime.now(), firstDate: DateTime(1950), // Set the first selectable date to a past date lastDate: DateTime(2100), // Set the last selectable date to a future date builder: (BuildContext context, Widget? child) { return Theme( data: ThemeData.dark().copyWith( colorScheme: ColorScheme.dark( primary: buttonColors, onPrimary: Colors.white, surface: buttonColors, onSurface: Colors.white, ), dialogBackgroundColor: primaryColor, ), child: child!, ); }, ); if (pickedDate != null) { print( pickedDate); //pickedDate output format => 2021-03-10 00:00:00.000 String formattedDate = DateFormat('dd-MM-yyyy').format(pickedDate); print( formattedDate); //formatted date output using intl package => 2021-03-16 setState(() { ending_dateController.text=formattedDate.toString(); }); } else {} }, ), ), ), ),//address description const SizedBox( height:15, ), Container( width:MediaQuery.of(context).size.width * .99, height: 55, padding: const EdgeInsets.fromLTRB(3, 0, 3, 0), child: ElevatedButton( style: ElevatedButton.styleFrom( primary: buttonColor, // background onPrimary: Colors.white, // foreground ), onPressed: () async { if (offer_nameController.text != '' && offer_codeController.text != '' && descriptionController.text != ''&& starting_dateController.text != '' && ending_dateController.text != '') { AppSettings.preLoaderDialog(context); /* var payload = new Map(); payload["offer_name"] = offer_nameController.text.toString(); payload["offer_code"] = offer_codeController.text.toString(); payload["description"] = descriptionController.text.toString();; payload["starting_date"] = starting_dateController.text.toString(); payload["ending_date"] = ending_dateController.text.toString(); payload["picture"] = [offerUrl]; payload["offer_status"] ="active"; print(payload);*/ Map payload = { "offer_name": offer_nameController.text.toString(), "offer_code": offer_codeController.text.toString(), "description":descriptionController.text.toString(), "starting_date":starting_dateController.text.toString(), "ending_date": ending_dateController.text.toString(), "category":dropdownTypeOfCategory.toString(), "picture": [ { "url": offerUrl } ], "offer_status": "active", }; bool offerStatus = await AppSettings.createOffers(payload); try{ if (offerStatus) { Navigator.of(context,rootNavigator: true).pop(); AppSettings.longSuccessToast("Offer Created Succesfully!!"); offer_nameController.text = '' ; offer_codeController.text = '' ; descriptionController.text = ''; starting_dateController.text = ''; ending_dateController.text = ''; Navigator.pop(context); Navigator.push( context, MaterialPageRoute(builder: (context) => Dashboard()), ); } else { Navigator.of(context,rootNavigator: true).pop(); AppSettings.longFailedToast("Please enter all fields"); } } catch(exception){ print(exception); AppSettings.longFailedToast("Please enter valid details"); Navigator.of(context,rootNavigator: true).pop(); } } else { AppSettings.longFailedToast("Offer Not Created!!"); Navigator.of(context,rootNavigator: true).pop(); } }, child: Text('Create'), )),//login button const SizedBox( height: 10, ), ], ), )), ), ])), ); } }