This commit is contained in:
Juan Felipe Duarte
2023-04-06 11:26:22 -05:00
parent de3d85f997
commit d83130b01d
8 changed files with 472 additions and 71 deletions
@@ -143,4 +143,17 @@ class AuthenticationRepository extends GetxController {
}
return city;
}
Future<String> getPhoto(String uid) async {
String photo = '';
try {
final snapshot =
await FirebaseFirestore.instance.collection('users').doc(uid).get();
final Map<String, dynamic>? data = snapshot.data();
photo = data?['photo'] ?? '';
} catch (e) {
print('Error getting photo: $e');
}
return photo;
}
}
+37
View File
@@ -0,0 +1,37 @@
import 'package:flutter/material.dart';
class PhotoViewWidget extends StatelessWidget {
Bytes imageData;
PhotoViewWidget({required this.imageData});
@override
Widget build(BuildContext context) {
return Container(
margin: EdgeInsets.symmetric(vertical: 50),
child: ClipOval(
child: Image.memory(
imageData,
width: 60,
height: 60,
fit: BoxFit.cover,
),
),
);
}
}
// Container(
// margin: EdgeInsets.symmetric(vertical: 50),
// width: 100,
// height: 100,
// decoration: BoxDecoration(
// color: Color(0xFF2BA4EC),
// borderRadius: BorderRadius.circular(50),
// ),
// child: Icon(
// Icons.person,
// color: Colors.white,
// size: 90,
// ),
// );
+301 -71
View File
@@ -1,11 +1,13 @@
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:intl_phone_field/countries.dart';
import 'dart:io';
import 'package:prosappco/src/authentication/authentication_repository.dart';
import 'package:prosappco/src/controllers/add_name_email_city.dart';
import 'package:prosappco/src/screens/welcome.dart';
import 'package:prosappco/src/services/select_image_profile.dart';
import 'package:prosappco/src/services/upload_image.dart';
class ProfileScreen extends StatefulWidget {
ProfileScreen({Key? key}) : super(key: key);
@@ -15,6 +17,10 @@ class ProfileScreen extends StatefulWidget {
}
class _ProfileScreenState extends State<ProfileScreen> {
File? imagen_to_upload;
bool _mostrarMenuDesplegable = true;
final uid = AuthenticationRepository.instance.getCurrentUserUid();
final _formKey = GlobalKey<FormState>();
final controller = Get.put(NameEmailCityController());
@@ -22,13 +28,16 @@ class _ProfileScreenState extends State<ProfileScreen> {
final _nameController = TextEditingController();
final _emailController = TextEditingController();
late final FirebaseAuth _auth;
final FirebaseStorage storage = FirebaseStorage.instance;
var photoTemp = '';
var _ciudad = '...';
var _photo = '...';
@override
void initState() {
super.initState();
_auth = FirebaseAuth.instance;
final Reference ref = storage.ref().child(_photo);
final currentUser = _auth.currentUser;
@@ -50,9 +59,148 @@ class _ProfileScreenState extends State<ProfileScreen> {
_ciudad = s;
}));
}
if (_photo == '...') {
AuthenticationRepository.instance
.getPhoto(uid.toString())
.then((String s) => setState(() {
_photo = s;
}));
}
}
Future<void> updateImage(image) async {
try {
await FirebaseFirestore.instance
.collection('users')
.doc(uid)
.update({'photo': image});
print('imagen actualizada correctamente');
} catch (e) {
try {
await FirebaseFirestore.instance
.collection('users')
.doc(uid)
.set({'photo': image});
} catch (e) {
print('Error al agregar la imagen de perfil: $e');
}
print('Error al actualizar la imagen de perfil: $e');
}
}
Future<bool> uploadImage(File image) async {
final String namefile = image.path.split('/').last;
Reference ref = storage.ref().child('profile').child(namefile);
final UploadTask uploadTask = ref.putFile(image);
final TaskSnapshot snapshot = await uploadTask.whenComplete(() => true);
photoTemp = ref.fullPath;
if (snapshot.state == TaskState.success) {
return true;
} else {
return false;
}
}
Future<Widget> downloadImage(Reference ref) async {
try {
if (_photo == '...' || _photo.isEmpty) {
return GestureDetector(
onTap: () {
_showChoiceDialog(context);
},
child: Container(
margin: EdgeInsets.symmetric(vertical: 50),
width: 100,
height: 100,
decoration: BoxDecoration(
color: Color(0xFF2BA4EC),
borderRadius: BorderRadius.circular(50),
),
child: Icon(
Icons.person,
color: Colors.white,
size: 90,
),
),
);
} else {
final imageData = await ref.getData();
if (imageData != null) {
// final widgetImage = Image.memory(imageData);
final widgetImage = GestureDetector(
onTap: () {
_showChoiceDialog(context);
},
child: Container(
margin: EdgeInsets.symmetric(vertical: 50),
child: ClipOval(
child: Image.memory(
imageData,
width: 60,
height: 60,
fit: BoxFit.cover,
),
),
),
);
return widgetImage;
} else {
return GestureDetector(
onTap: () {
_showChoiceDialog(context);
},
child: Container(
margin: EdgeInsets.symmetric(vertical: 50),
width: 100,
height: 100,
decoration: BoxDecoration(
color: Color(0xFF2BA4EC),
borderRadius: BorderRadius.circular(50),
),
child: Icon(
Icons.person,
color: Colors.white,
size: 90,
),
),
);
}
}
} catch (e) {
print('XD $e');
return GestureDetector(
onTap: () {
_showChoiceDialog(context);
},
child: Container(
margin: EdgeInsets.symmetric(vertical: 50),
width: 100,
height: 100,
decoration: BoxDecoration(
color: Color(0xFF2BA4EC),
borderRadius: BorderRadius.circular(50),
),
child: Icon(
Icons.person,
color: Colors.white,
size: 90,
),
),
);
}
}
Future<void> updateInfo() async {
final currentUser = _auth.currentUser;
String newName = _nameController.text.trim();
String newEmail = _emailController.text.trim();
@@ -71,46 +219,99 @@ class _ProfileScreenState extends State<ProfileScreen> {
return;
}
try {
await FirebaseAuth.instance.currentUser!.updateDisplayName(newName);
await FirebaseFirestore.instance.collection('users').doc(uid).update({
'name': newName,
});
print('Nombre actualizado correctamente');
} catch (e) {
print('Error al actualizar el nombre: $e');
if (currentUser?.displayName != newName) {
try {
await FirebaseAuth.instance.currentUser!.updateDisplayName(newName);
await FirebaseFirestore.instance.collection('users').doc(uid).update({
'name': newName,
});
print('Nombre actualizado correctamente');
} catch (e) {
print('Error al actualizar el nombre: $e');
}
}
if (currentUser?.email != newEmail) {
AuthCredential credential =
EmailAuthProvider.credential(email: newEmail, password: '654321');
try {
await FirebaseAuth.instance.currentUser!.updateEmail(newEmail);
await FirebaseFirestore.instance.collection('users').doc(uid).update({
'email': newEmail,
});
print('Correo electrónico actualizado correctamente');
// Reautentica al usuario con las credenciales proporcionadas
await FirebaseAuth.instance.currentUser!
.reauthenticateWithCredential(credential);
// Actualiza el correo electrónico del usuario
await FirebaseAuth.instance.currentUser!.updateEmail(newEmail);
// Actualiza los datos del usuario en tu base de datos
await FirebaseFirestore.instance.collection('users').doc(uid).update({
'email': newEmail,
});
print('Correo electrónico actualizado correctamente');
} catch (e) {
print('Error al actualizar el correo electrónico: $e');
}
}
try {
await FirebaseAuth.instance.currentUser!.updateEmail(newEmail);
await FirebaseFirestore.instance.collection('users').doc(uid).update({
'email': newEmail,
});
print('Correo electrónico actualizado correctamente');
if (imagen_to_upload == null) {
return;
} else {
final uploaded = await uploadImage(imagen_to_upload!);
updateImage(photoTemp);
}
} catch (e) {
print('Error al actualizar el correo electrónico: $e');
print('Error al actualizar la imagen de perfil $e');
}
}
AuthCredential credential =
EmailAuthProvider.credential(email: newEmail, password: '654321');
try {
// Reautentica al usuario con las credenciales proporcionadas
await FirebaseAuth.instance.currentUser!
.reauthenticateWithCredential(credential);
// Actualiza el correo electrónico del usuario
await FirebaseAuth.instance.currentUser!.updateEmail(newEmail);
// Actualiza los datos del usuario en tu base de datos
await FirebaseFirestore.instance.collection('users').doc(uid).update({
'email': newEmail,
});
print('Correo electrónico actualizado correctamente');
} catch (e) {
print('Error al actualizar el correo electrónico: $e');
}
Future<void> _showChoiceDialog(BuildContext context) async {
return showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
content: SingleChildScrollView(
child: ListBody(
children: [
GestureDetector(
child: Text(
textAlign: TextAlign.center,
"Tomar foto",
style: TextStyle(color: Color(0xFF2BA4EC)),
),
onTap: () async {
final imagen = await getImage(1);
setState(() {
imagen_to_upload = File(imagen!.path);
});
},
),
Divider(color: Colors.black54),
GestureDetector(
child: Text(
textAlign: TextAlign.center,
"Abrir Galería",
style: TextStyle(color: Color(0xFF2BA4EC)),
),
onTap: () async {
final imagen = await getImage(2);
setState(() {
imagen_to_upload = File(imagen!.path);
});
},
),
],
),
),
);
},
);
}
@override
@@ -123,16 +324,17 @@ class _ProfileScreenState extends State<ProfileScreen> {
child: Scaffold(
resizeToAvoidBottomInset: false,
appBar: AppBar(
backgroundColor: Colors.white,
iconTheme: IconThemeData(
backgroundColor: Colors.white,
iconTheme: IconThemeData(
color: Colors.black,
),
title: Text(
'Perfil',
style: TextStyle(
color: Colors.black,
),
title: Text(
'Perfil',
style: TextStyle(
color: Colors.black,
),
)),
),
),
drawer: Drawer(
child: ListView(
padding: EdgeInsets.zero,
@@ -162,18 +364,31 @@ class _ProfileScreenState extends State<ProfileScreen> {
),
],
),
leading: Container(
width: 60,
height: 60,
decoration: BoxDecoration(
color: Color(0xFF2BA4EC),
borderRadius: BorderRadius.circular(50),
),
child: Icon(
Icons.person,
color: Colors.white,
size: 55,
),
leading: FutureBuilder<Widget>(
future:
downloadImage(storage.ref().child(_photo)),
builder: (BuildContext context,
AsyncSnapshot<Widget> snapshot) {
if (snapshot.connectionState ==
ConnectionState.done &&
snapshot.hasData) {
return snapshot.data!;
} else {
return Container(
width: 60,
height: 60,
decoration: BoxDecoration(
color: Color(0xFF2BA4EC),
borderRadius: BorderRadius.circular(50),
),
child: Icon(
Icons.person,
color: Colors.white,
size: 55,
),
);
}
},
),
trailing: Icon(Icons.keyboard_arrow_right,
color: Colors.black),
@@ -340,20 +555,35 @@ class _ProfileScreenState extends State<ProfileScreen> {
body: Center(
child: Column(
children: [
Container(
margin: EdgeInsets.symmetric(vertical: 50),
width: 100,
height: 100,
decoration: BoxDecoration(
color: Color(0xFF2BA4EC),
borderRadius: BorderRadius.circular(50),
),
child: Icon(
Icons.person,
color: Colors.white,
size: 90,
),
),
imagen_to_upload != null
? GestureDetector(
onTap: () {
_showChoiceDialog(context);
},
child: Container(
margin: EdgeInsets.symmetric(vertical: 50),
child: ClipOval(
child: Image.file(
imagen_to_upload!,
width: 100,
height: 100,
fit: BoxFit.cover,
),
),
),
)
: FutureBuilder<Widget>(
future: downloadImage(storage.ref().child(_photo)),
builder: (BuildContext context,
AsyncSnapshot<Widget> snapshot) {
if (snapshot.connectionState == ConnectionState.done &&
snapshot.hasData) {
return snapshot.data!;
} else {
return const CircularProgressIndicator();
}
},
),
Container(
width: 300,
padding: EdgeInsets.only(top: 0),
@@ -0,0 +1,13 @@
import 'package:image_picker/image_picker.dart';
Future<XFile?> getImage(opc) async {
final ImagePicker picker = ImagePicker();
if (opc == 1) {
XFile? image = await picker.pickImage(source: ImageSource.camera);
return image;
} else {
XFile? image = await picker.pickImage(source: ImageSource.gallery);
return image;
}
}
+24
View File
@@ -0,0 +1,24 @@
import 'dart:io';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_storage/firebase_storage.dart';
// final FirebaseStorage storage = FirebaseStorage.instance;
// Future<bool> uploadImage(File image) async {
// final String namefile = image.path.split('/').last;
// Reference ref = storage.ref().child('profile').child(namefile);
// final UploadTask uploadTask = ref.putFile(image);
// final TaskSnapshot snapshot = await uploadTask.whenComplete(() => true);
// final String url = await snapshot.ref.getDownloadURL();
// if (snapshot.state == TaskState.success) {
// return true;
// } else {
// return false;
// }
// }