import 'package:flutter/material.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:http/http.dart' as http; import 'package:intl/intl.dart'; import 'dart:convert'; import 'dart:io'; import 'dart:typed_data'; import '../classes/alert.dart'; import '../classes/eventAdded.dart'; import '../variable/globals.dart' as globals; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { Map events = {}; String imagePath = ""; @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, home: UpdateeventImage(events: events, imagePath: imagePath), ); } } class UpdateeventImage extends StatefulWidget { const UpdateeventImage( {Key? key, required this.events, required this.imagePath}) : super(key: key); final Map events; final String imagePath; @override _UpdateeventImageState createState() => _UpdateeventImageState(); } class _UpdateeventImageState extends State with ShowErrorDialog, ShowEventDialog { TextEditingController inputName = TextEditingController(); TextEditingController inputAddress = TextEditingController(); TextEditingController inputZipCode = TextEditingController(); TextEditingController inputCity = TextEditingController(); TextEditingController inputCountry = TextEditingController(); TextEditingController inputDate = TextEditingController(); TextEditingController inputDesc = TextEditingController(); TextEditingController startDatepicker = TextEditingController(); TextEditingController startTimepicker = TextEditingController(); TextEditingController endDatepicker = TextEditingController(); TextEditingController endTimepicker = TextEditingController(); onTapFunctionDatePicker( {required BuildContext context, required String position}) async { DateTime? pickedDate = await showDatePicker( context: context, firstDate: DateTime.parse(widget.events["date"]), initialDate: DateTime.parse(widget.events["date"]), lastDate: DateTime(2104)); if (pickedDate == null) return; if (position == "start") { startDatepicker.text = DateFormat("dd-MM-yyyy").format(pickedDate); } if (position == "end") { endDatepicker.text = DateFormat("dd-MM-yyyy").format(pickedDate); } } onTapFunctionTimePicker( {required BuildContext context, required String position}) async { TimeOfDay? pickedDate = await showTimePicker( context: context, initialTime: TimeOfDay.fromDateTime(DateTime.parse(widget.events["date"]))); if (pickedDate == null) return; if (position == "start") { startTimepicker.text = pickedDate.format(context); } if (position == "end") { endTimepicker.text = pickedDate.format(context); } } String formatDate(String date) { var splitedDate = date.split("-"); var day = splitedDate[0]; var month = splitedDate[1]; var year = splitedDate[2]; return "${year}-${month}-${day}"; } Future _updateEvent(BuildContext context) async { var url = Uri.parse("${globals.api}/token"); var name = inputName.text; var place = inputAddress.text; var city = inputCity.text; var country = inputCountry.text; var zipCode = inputZipCode.text; var description = inputDesc.text; var startDateFormat = formatDate(startDatepicker.text); var endDateFormat = formatDate(endDatepicker.text); var startDate = "${startDateFormat}T${startTimepicker.text.replaceAll('-', ':')}"; var endDate = "${endDateFormat}T${endTimepicker.text.replaceAll('-', ':')}"; print("start date : ${startDate}"); print("end date : ${endDate}"); SharedPreferences prefs = await SharedPreferences.getInstance(); var accessToken = prefs.getString("access_token") ?? ""; List send = ["toto"]; if (accessToken.isNotEmpty) { try { final params = { 'expiration': '600', 'key': '87a91f7e54516808dda2c4feffbd5287', }; final urlPost = Uri.parse('https://api.imgbb.com/1/upload') .replace(queryParameters: params); File image = File(widget.imagePath); Uint8List _bytes = await image.readAsBytes(); String _base64String = base64.encode(_bytes); final req = http.MultipartRequest('POST', url) ..fields['image'] = _base64String; final stream = await req.send(); final res = await http.Response.fromStream(stream); final status = res.statusCode; if (status == 200) { //String credentials = "${pseudo}:${password}"; //Codec stringToBase64 = utf8.fuse(base64); //String encoded = stringToBase64.encode(credentials); var urlPut = Uri.parse("${globals.api}/events"); var responsePut = await http.put(urlPut, headers: { HttpHeaders.cookieHeader: 'access_token=${accessToken}', HttpHeaders.acceptHeader: 'application/json, text/plain, */*', HttpHeaders.contentTypeHeader: 'application/json' }, body: jsonEncode({ 'name': name, 'place': place, 'start_date': startDate, 'end_date': endDate, 'zip_code': zipCode, 'country': country, 'city': city, 'organizers': send, 'latitude': '0.0', 'longitude': '0.0', 'description': description })); print(responsePut.statusCode); if ((responsePut.statusCode == 200) || (responsePut.statusCode == 201)) { showEventDialog(context, "Evenement ${name} ajoute"); } else { var text = ""; switch (responsePut.statusCode) { case 400: { text = "Requête mal construite"; } break; case 406: { text = "Mot de passe incorrect"; } break; case 404: { text = "Utilisateur inconnu"; } break; case 403: { text = "Utilisateur desactive"; } break; case 410: { text = "Token invalide"; } break; case 500: { text = "Probleme interne du serveur"; } break; default: { text = "Probleme d'authentification inconnu"; } break; } showErrorDialog(context, text); } } else { print("imgbb error : ${status}"); } } catch (e) { showErrorDialog(context, "${e}"); } } else { showErrorDialog(context, "Champ vide"); } } void start() async { inputName.text = widget.events["name"]; inputCity.text = widget.events["city"]; inputAddress.text = widget.events["address"]; inputZipCode.text = widget.events["zip_code"]; inputCountry.text = widget.events["country"]; inputDesc.text = widget.events["description"]; DateTime pickedStartDate = DateTime.parse(widget.events["start_date"]); DateTime pickedEndDate = DateTime.parse(widget.events["end_date"]); startDatepicker.text = DateFormat("dd-MM-yyyy").format(pickedStartDate); endDatepicker.text = DateFormat("dd-MM-yyyy").format(pickedEndDate); startTimepicker.text = DateFormat("HH-mm").format(pickedStartDate); endTimepicker.text = DateFormat("HH-mm").format(pickedEndDate); } @override void initState() { start(); super.initState(); } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.white, appBar: AppBar( title: Text("Add or Update a event"), backgroundColor: Colors.blue, foregroundColor: Colors.white, ), body: SingleChildScrollView( child: Column( children: [ Padding( padding: const EdgeInsets.only(top: 60.0), child: Center( child: Container( width: 200, height: 150, decoration: BoxDecoration( borderRadius: BorderRadius.circular(100.0)), child: Image.file(File(widget.imagePath))), ), ), Padding( //padding: const EdgeInsets.only(left:15.0,right: 15.0,top:0,bottom: 0), padding: EdgeInsets.symmetric(horizontal: 15), child: TextField( controller: inputName, decoration: InputDecoration( border: OutlineInputBorder(), labelText: 'Nom', hintText: 'Modifier le nom de l\'évènement'), ), ), Padding( padding: const EdgeInsets.only( left: 15.0, right: 15.0, top: 15, bottom: 0), //padding: EdgeInsets.symmetric(horizontal: 15), child: TextField( controller: inputAddress, decoration: InputDecoration( border: OutlineInputBorder(), labelText: 'Adresse', hintText: 'Entrer une adresse'), ), ), Padding( padding: const EdgeInsets.only( left: 15.0, right: 15.0, top: 15, bottom: 0), //padding: EdgeInsets.symmetric(horizontal: 15), child: TextField( controller: inputZipCode, decoration: InputDecoration( border: OutlineInputBorder(), labelText: 'Code postal', hintText: 'Entrer un code postal'), ), ), Padding( padding: const EdgeInsets.only( left: 15.0, right: 15.0, top: 15, bottom: 0), //padding: EdgeInsets.symmetric(horizontal: 15), child: TextField( controller: inputCity, decoration: InputDecoration( border: OutlineInputBorder(), labelText: 'Ville', hintText: 'Entrer une ville'), ), ), Padding( padding: const EdgeInsets.only( left: 15.0, right: 15.0, top: 15, bottom: 0), //padding: EdgeInsets.symmetric(horizontal: 15), child: TextField( controller: inputCountry, decoration: InputDecoration( border: OutlineInputBorder(), labelText: 'Pays', hintText: 'Entrer un pays'), ), ), Padding( padding: const EdgeInsets.only( left: 15.0, right: 15.0, top: 15, bottom: 0), //padding: EdgeInsets.symmetric(horizontal: 15), child: TextField( controller: startDatepicker, readOnly: true, decoration: InputDecoration( border: OutlineInputBorder(), labelText: 'Date de debut de l\'évènement', hintText: 'Cliquez ici pour selectionner une date'), onTap: () => onTapFunctionDatePicker( context: context, position: "start")), ), Padding( padding: const EdgeInsets.only( left: 15.0, right: 15.0, top: 15, bottom: 0), //padding: EdgeInsets.symmetric(horizontal: 15), child: TextField( controller: startTimepicker, readOnly: true, decoration: InputDecoration( border: OutlineInputBorder(), labelText: 'Heure de debut de l\'évènement', hintText: 'Cliquez ici pour selectionner une heure'), onTap: () => onTapFunctionTimePicker( context: context, position: "start")), ), Padding( padding: const EdgeInsets.only( left: 15.0, right: 15.0, top: 15, bottom: 0), //padding: EdgeInsets.symmetric(horizontal: 15), child: TextField( controller: endDatepicker, readOnly: true, decoration: InputDecoration( border: OutlineInputBorder(), labelText: 'Date de fin de l\'évènement', hintText: 'Cliquez ici pour selectionner une date'), onTap: () => onTapFunctionDatePicker( context: context, position: "end")), ), Padding( padding: const EdgeInsets.only( left: 15.0, right: 15.0, top: 15, bottom: 0), //padding: EdgeInsets.symmetric(horizontal: 15), child: TextField( controller: endTimepicker, readOnly: true, decoration: InputDecoration( border: OutlineInputBorder(), labelText: 'Heure de fin de l\'évènement', hintText: 'Cliquez ici pour selectionner une heure'), onTap: () => onTapFunctionTimePicker( context: context, position: "end")), ), Padding( padding: const EdgeInsets.only( left: 15.0, right: 15.0, top: 15, bottom: 0), //padding: EdgeInsets.symmetric(horizontal: 15), child: TextField( controller: inputDesc, keyboardType: TextInputType.multiline, maxLines: 10, decoration: InputDecoration( border: OutlineInputBorder(), labelText: 'Description', hintText: 'Décrire l\'evènement'), ), ), SizedBox( height: 30, ), Container( height: 50, width: 250, decoration: BoxDecoration( color: Colors.blue, borderRadius: BorderRadius.circular(20)), child: TextButton( onPressed: () { _updateEvent(context); }, child: Text( 'Ajouter', style: TextStyle(color: Colors.white, fontSize: 25), ), ), ) ], ), ), ); } }