import 'package:covas_mobile/classes/MyDrawer.dart'; 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 '../classes/MyDrawer.dart'; import '../main.dart'; import '../classes/alert.dart'; import '../classes/eventAdded.dart'; import '../variable/globals.dart' as globals; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, home: EditProfile(), ); } } class EditProfile extends StatefulWidget { const EditProfile({super.key}); @override _EditProfileState createState() => _EditProfileState(); } class _EditProfileState extends State with ShowAlertDialog, ShowEventDialog { TextEditingController inputUserName = TextEditingController(); TextEditingController inputName = TextEditingController(); TextEditingController inputFirstName = TextEditingController(); TextEditingController inputEmail = TextEditingController(); TextEditingController inputBirth = TextEditingController(); TextEditingController inputPassword = TextEditingController(); TextEditingController inputPasswordConfirmed = TextEditingController(); onTapFunctionDatePicker({required BuildContext context}) async { DateTime initialDate = DateTime.parse(formatDate(inputBirth.text)); DateTime? pickedDate = await showDatePicker( context: context, firstDate: DateTime(1900), initialDate: initialDate, lastDate: DateTime(2104)); if (pickedDate == null) return; inputBirth.text = DateFormat("dd/MM/yyyy").format(pickedDate); } convertNulltoEmptyString(var check) { if (check == null) { return ""; } return check; } convertNulltoArray(List check) { if (check == null) { return []; } return check; } 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 _updateProfile(BuildContext context) async { var username = inputUserName.text; var firstName = inputFirstName.text; var name = inputName.text; var email = inputEmail.text; var password = inputPassword.text; var confirmedPassword = inputPasswordConfirmed.text; var birth = DateTime.parse(formatDate(inputBirth.text)); if ((password.isNotEmpty) && (confirmedPassword.isNotEmpty)) { if (password != confirmedPassword) { showAlertDialog(context, "Erreur", "Mot de passe different"); return; } } var urlPut = Uri.parse("${globals.api}/users/me"); SharedPreferences prefs = await SharedPreferences.getInstance(); var accessToken = prefs.getString("access_token") ?? ""; if (accessToken.isNotEmpty) { 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, 'username': username, 'firstName': firstName, 'password': password, 'email': email, 'roles': '', 'birth': birth.toString() })); print(responsePut.statusCode); if (responsePut.statusCode == 200) { showEventDialog(context, "Votre utilisateur a été modifié"); Navigator.pushReplacement( context, MaterialPageRoute(builder: (_) => EditProfile())); return; } final errorMessages = { 400: "Requête mal construite", 406: "Mot de passe incorrect", 404: "Utilisateur inconnu", 403: "Utilisateur désactivé", 410: "Token invalide", 500: "Problème interne du serveur", }; final text = errorMessages[responsePut.statusCode] ?? "Problème d'authentification inconnu"; showAlertDialog(context, "Erreur serveur", text); } else { Navigator.pushReplacement( context, MaterialPageRoute(builder: (_) => LoginDemo())); } } Future _getInfoProfile() async { var urlGet = Uri.parse("${globals.api}/users/me"); SharedPreferences prefs = await SharedPreferences.getInstance(); var accessToken = prefs.getString("access_token") ?? ""; if (accessToken.isNotEmpty) { var responseGet = await http.get(urlGet, headers: { HttpHeaders.cookieHeader: 'access_token=${accessToken}', HttpHeaders.acceptHeader: 'application/json, text/plain, */*', HttpHeaders.contentTypeHeader: 'application/json' }); print(responseGet.statusCode); if (responseGet.statusCode == 200) { var body = json.decode(utf8.decode(responseGet.bodyBytes)); setState(() { inputName.text = body["name"]; inputFirstName.text = body["firstName"]; inputUserName.text = body["username"]; inputEmail.text = body["email"]; inputBirth.text = DateFormat("dd/MM/yyyy").format(DateTime.parse(body["birth"])); }); return; } final errorMessages = { 400: "Requête mal construite", 406: "Mot de passe incorrect", 404: "Utilisateur inconnu", 403: "Utilisateur désactivé", 410: "Token invalide", 500: "Problème interne du serveur", }; final text = errorMessages[responseGet.statusCode] ?? "Problème d'authentification inconnu"; showAlertDialog(context, "Erreur serveur", text); } else { Navigator.pushReplacement( context, MaterialPageRoute(builder: (_) => LoginDemo())); } } @override void initState() { super.initState(); _getInfoProfile(); } final _formKey = GlobalKey(); String? _validateField(String? value) { return value!.isEmpty ? 'Champ requis' : null; } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.white, appBar: AppBar( title: Text("Update profile"), backgroundColor: Colors.blue, foregroundColor: Colors.white, ), drawer: MyDrawer(), body: Form( key: _formKey, child: SingleChildScrollView( child: Column( children: [ Padding( padding: const EdgeInsets.only( left: 15.0, right: 15.0, top: 15, bottom: 0), //padding: EdgeInsets.symmetric(horizontal: 15), child: TextFormField( controller: inputUserName, validator: (value) => _validateField(value), decoration: InputDecoration( border: OutlineInputBorder(), labelText: 'Pseudo', hintText: 'Modifier le pseudo'), ), ), Padding( padding: const EdgeInsets.only( left: 15.0, right: 15.0, top: 15, bottom: 0), //padding: EdgeInsets.symmetric(horizontal: 15), child: TextFormField( controller: inputPassword, obscureText: true, decoration: InputDecoration( border: OutlineInputBorder(), labelText: 'Mot de passe', hintText: 'Entrez le mot de passe'), ), ), Padding( padding: const EdgeInsets.only( left: 15.0, right: 15.0, top: 15, bottom: 0), //padding: EdgeInsets.symmetric(horizontal: 15), child: TextFormField( controller: inputPasswordConfirmed, obscureText: true, decoration: InputDecoration( border: OutlineInputBorder(), labelText: 'Confirmez le mot de passe', hintText: 'Confirmez le mot de passe'), ), ), Padding( padding: const EdgeInsets.only( left: 15.0, right: 15.0, top: 15, bottom: 0), //padding: EdgeInsets.symmetric(horizontal: 15), child: TextFormField( controller: inputName, validator: (value) => _validateField(value), decoration: InputDecoration( border: OutlineInputBorder(), labelText: 'Nom', hintText: 'Modifier le nom'), ), ), Padding( padding: const EdgeInsets.only( left: 15.0, right: 15.0, top: 15, bottom: 0), //padding: EdgeInsets.symmetric(horizontal: 15), child: TextFormField( controller: inputFirstName, validator: (value) => _validateField(value), decoration: InputDecoration( border: OutlineInputBorder(), labelText: 'Prénom', hintText: 'Modifier le prénom'), ), ), Padding( padding: const EdgeInsets.only( left: 15.0, right: 15.0, top: 15, bottom: 0), //padding: EdgeInsets.symmetric(horizontal: 15), child: TextFormField( controller: inputEmail, validator: (value) => _validateField(value), decoration: InputDecoration( border: OutlineInputBorder(), labelText: 'Email', hintText: 'Modifier l\'adresse mail'), ), ), Padding( padding: const EdgeInsets.only( left: 15.0, right: 15.0, top: 15, bottom: 0), //padding: EdgeInsets.symmetric(horizontal: 15), child: TextFormField( controller: inputBirth, readOnly: true, validator: (value) => _validateField(value), decoration: InputDecoration( border: OutlineInputBorder(), labelText: 'Date de naissance', hintText: 'Cliquez ici pour selectionner une date'), onTap: () => onTapFunctionDatePicker(context: context)), ), SizedBox( height: 30, ), Container( height: 50, width: 250, decoration: BoxDecoration( color: Colors.blue, borderRadius: BorderRadius.circular(20)), child: TextButton( onPressed: () { if (_formKey.currentState!.validate()) { _updateProfile(context); } }, child: Text( 'Modifier le profil', style: TextStyle(color: Colors.white, fontSize: 25), ), ), ) ], ), ), )); } }