after rediense

This commit is contained in:
Felipe
2024-02-26 16:32:31 -05:00
parent a1e367bdf3
commit 11d9ee6d35
11 changed files with 256 additions and 223 deletions
+10 -9
View File
@@ -30,15 +30,16 @@ class ProfileBloc extends Bloc<ProfileEvent, ProfileState> {
UpdateUserInfo event, Emitter<ProfileState> emit) async { UpdateUserInfo event, Emitter<ProfileState> emit) async {
emit(UpdateUserInfoLoading()); emit(UpdateUserInfoLoading());
try { try {
await _userRepository.updateUserInfo(event.userId, event.picture, { final userImageUrl = event.filePicture != null
'name': event.name, ? await _userRepository.uploadPicture(
// 'picture': event.picture, event.filePicture!, event.myUser.id)
'nickname': event.nickname, : null;
'email': event.email,
'phone': event.phone, final myUser = userImageUrl == null
'birthDate': event.birthDate, ? event.myUser
'gender': event.gender : event.myUser.copyWith(picture: userImageUrl);
});
await _userRepository.updateUserInfo(myUser);
emit(const UpdateUserInfoSuccess()); emit(const UpdateUserInfoSuccess());
} catch (e) { } catch (e) {
emit(UpdateUserInfoFailure()); emit(UpdateUserInfoFailure());
+5 -28
View File
@@ -7,38 +7,15 @@ abstract class ProfileEvent extends Equatable {
List<Object?> get props => []; List<Object?> get props => [];
} }
class UploadPicture extends ProfileEvent {
final String file;
final String userId;
const UploadPicture(this.file, this.userId);
@override
List<Object?> get props => [file, userId];
}
class UpdateUserInfo extends ProfileEvent { class UpdateUserInfo extends ProfileEvent {
final String userId; final MyUser myUser;
final String picture; final String? filePicture;
final String? name;
final String? nickname;
final String? email;
final String? phone;
final String? birthDate;
final String? gender;
const UpdateUserInfo({ const UpdateUserInfo({
required this.userId, required this.myUser,
required this.picture, this.filePicture,
this.name,
this.nickname,
this.email,
this.phone,
this.birthDate,
this.gender,
}); });
@override @override
List<Object?> get props => List<Object?> get props => [myUser, filePicture];
[userId, name, nickname, email, phone, picture, birthDate, gender];
} }
-13
View File
@@ -9,19 +9,6 @@ abstract class ProfileState extends Equatable {
class UpdateUserInfoInitial extends ProfileState {} class UpdateUserInfoInitial extends ProfileState {}
class UploadPictureFailure extends ProfileState {}
class UploadPictureLoading extends ProfileState {}
class UploadPictureSuccess extends ProfileState {
final String userImage;
const UploadPictureSuccess(this.userImage);
@override
List<Object> get props => [userImage];
}
class UpdateUserInfoFailure extends ProfileState {} class UpdateUserInfoFailure extends ProfileState {}
class UpdateUserInfoLoading extends ProfileState {} class UpdateUserInfoLoading extends ProfileState {}
@@ -1,17 +1,17 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
class BirthDatePicker extends StatefulWidget { class BirthdayPicker extends StatefulWidget {
final Function(DateTime) onDateSelected; final Function(DateTime) onDateSelected;
final TextEditingController controller; final TextEditingController controller;
const BirthDatePicker( const BirthdayPicker(
{super.key, required this.onDateSelected, required this.controller}); {super.key, required this.onDateSelected, required this.controller});
@override @override
State<BirthDatePicker> createState() => _BirthDatePickerState(); State<BirthdayPicker> createState() => _BirthdayPickerState();
} }
class _BirthDatePickerState extends State<BirthDatePicker> { class _BirthdayPickerState extends State<BirthdayPicker> {
DateTime selectedDate = DateTime selectedDate =
DateTime.now().subtract(const Duration(days: 365 * 20)); DateTime.now().subtract(const Duration(days: 365 * 20));
+42 -33
View File
@@ -9,6 +9,7 @@ class GeneralDrawerHeader extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final user = context.read<MyUserBloc>().state.user!;
return ListTile( return ListTile(
onTap: () { onTap: () {
Navigator.pop(context); Navigator.pop(context);
@@ -22,46 +23,54 @@ class GeneralDrawerHeader extends StatelessWidget {
); );
}, },
title: Text( title: Text(
context.read<MyUserBloc>().state.user!.name ?? '', user.name ?? '',
style: const TextStyle(fontWeight: FontWeight.bold), style: const TextStyle(fontWeight: FontWeight.bold),
), ),
subtitle: Text( subtitle: Text(
context.read<MyUserBloc>().state.user!.email ?? user.drawerLabel,
context.read<MyUserBloc>().state.user!.phone ??
'',
style: const TextStyle(fontSize: 12), style: const TextStyle(fontSize: 12),
), ),
leading: context.read<MyUserBloc>().state.user!.picture == "" || leading: pictureWidget(user.picture, context),
context.read<MyUserBloc>().state.user!.picture == null
? Container(
width: 80,
height: 80,
decoration: BoxDecoration(
color: Colors.grey.shade300,
shape: BoxShape.circle,
),
child: Icon(
CupertinoIcons.person,
color: Colors.grey.shade400,
size: 35,
),
)
: Container(
width: 60,
height: 60,
decoration: BoxDecoration(
color: Colors.grey,
shape: BoxShape.circle,
image: DecorationImage(
image: NetworkImage(
context.read<MyUserBloc>().state.user?.picture ?? '',
),
fit: BoxFit.cover,
),
),
),
trailing: const Icon(Icons.keyboard_arrow_right, color: Colors.black), trailing: const Icon(Icons.keyboard_arrow_right, color: Colors.black),
contentPadding: const EdgeInsets.symmetric(vertical: 10, horizontal: 15), contentPadding: const EdgeInsets.symmetric(vertical: 10, horizontal: 15),
); );
} }
Widget pictureWidget(String? pictureUrl, BuildContext context) {
ImageProvider<Object>? imageProvider;
if (pictureUrl != null && pictureUrl.isNotEmpty) {
imageProvider = NetworkImage(pictureUrl);
}
return pictureContainerWidget(imageProvider);
}
Widget pictureContainerWidget(ImageProvider<Object>? imageProvider) {
final image = imageProvider == null
? null
: DecorationImage(
image: imageProvider,
fit: BoxFit.contain,
);
final widget = image == null
? Icon(
CupertinoIcons.person,
color: Colors.grey.shade400,
size: 40,
)
: null;
return Container(
width: 60,
height: 60,
decoration: BoxDecoration(
color: Colors.grey.shade300,
shape: BoxShape.circle,
image: image,
),
child: widget,
);
}
} }
+145 -101
View File
@@ -7,9 +7,8 @@ import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:image_picker/image_picker.dart'; import 'package:image_picker/image_picker.dart';
import 'package:prosappco/blocs/my_user_bloc/my_user_bloc.dart'; import 'package:prosappco/blocs/my_user_bloc/my_user_bloc.dart';
import 'package:prosappco/blocs/profile_bloc/profile_bloc.dart'; import 'package:prosappco/blocs/profile_bloc/profile_bloc.dart';
import 'package:prosappco/components/birth_date_picker.dart'; import 'package:prosappco/components/birthday_picker.dart';
import 'package:prosappco/components/gender_dropdown.dart'; import 'package:prosappco/components/gender_dropdown.dart';
import 'package:prosappco/components/general_primary_button.dart';
import 'package:prosappco/src/components/pop_appbar.dart'; import 'package:prosappco/src/components/pop_appbar.dart';
class ProfileScreen extends StatefulWidget { class ProfileScreen extends StatefulWidget {
@@ -23,16 +22,17 @@ class _ProfileScreenState extends State<ProfileScreen> {
final TextEditingController _nameController = TextEditingController(); final TextEditingController _nameController = TextEditingController();
final TextEditingController _emailController = TextEditingController(); final TextEditingController _emailController = TextEditingController();
final TextEditingController _phoneController = TextEditingController(); final TextEditingController _phoneController = TextEditingController();
final TextEditingController _birthDateController = TextEditingController(); final TextEditingController _birthdayController = TextEditingController();
final TextEditingController _genderController = TextEditingController(); final TextEditingController _genderController = TextEditingController();
XFile? _imageFile; XFile? _imageFile;
bool isLoading = false;
@override @override
void dispose() { void dispose() {
_nameController.dispose(); _nameController.dispose();
_emailController.dispose(); _emailController.dispose();
_phoneController.dispose(); _phoneController.dispose();
_birthDateController.dispose(); _birthdayController.dispose();
_genderController.dispose(); _genderController.dispose();
super.dispose(); super.dispose();
} }
@@ -41,8 +41,25 @@ class _ProfileScreenState extends State<ProfileScreen> {
Widget build(BuildContext context) { Widget build(BuildContext context) {
return BlocListener<ProfileBloc, ProfileState>( return BlocListener<ProfileBloc, ProfileState>(
listener: (context, state) { listener: (context, state) {
if (state is UploadPictureSuccess) { if (state is UpdateUserInfoLoading) {
setState(() {}); setState(() {
isLoading = true;
});
} else if (state is UpdateUserInfoSuccess) {
// Snack bar
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
content: Text('Información actualizada'),
));
setState(() {
isLoading = false;
});
} else if (state is UpdateUserInfoFailure) {
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
content: Text('Error al actualizar la información'),
));
setState(() {
isLoading = false;
});
} }
}, },
child: Scaffold( child: Scaffold(
@@ -60,75 +77,12 @@ class _ProfileScreenState extends State<ProfileScreen> {
return SingleChildScrollView( return SingleChildScrollView(
child: Padding( child: Padding(
padding: const EdgeInsets.all(20.0), padding:
const EdgeInsets.symmetric(horizontal: 40, vertical: 20),
child: Column( child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch, crossAxisAlignment: CrossAxisAlignment.stretch,
children: [ children: [
GestureDetector( pictureWidget(state, context),
onTap: () async {
final ImagePicker picker = ImagePicker();
final XFile? image = await picker.pickImage(
source: ImageSource.gallery,
maxHeight: 500,
maxWidth: 500,
imageQuality: 40,
);
if (image != null) {
// context
// .read<ProfileBloc>()
// .add(UploadPicture(image.path, state.user!.id));
setState(() {
_imageFile = image;
});
}
},
child: state.user!.picture == "" ||
state.user!.picture == null
? _imageFile != null
? Container(
width: 150,
height: 150,
decoration: BoxDecoration(
color: Colors.grey,
shape: BoxShape.circle,
image: DecorationImage(
image: FileImage(File(_imageFile!.path)),
fit: BoxFit.contain,
),
),
)
: Container(
width: 120,
height: 120,
decoration: BoxDecoration(
color: Colors.grey.shade300,
shape: BoxShape.circle,
),
child: Icon(
CupertinoIcons.person,
color: Colors.grey.shade400,
size: 40,
),
)
: Container(
width: 150,
height: 150,
decoration: BoxDecoration(
color: Colors.grey,
shape: BoxShape.circle,
image: DecorationImage(
image: NetworkImage(context
.read<MyUserBloc>()
.state
.user
?.picture ??
''),
fit: BoxFit.contain,
),
),
),
),
const SizedBox(height: 20.0), const SizedBox(height: 20.0),
TextFormField( TextFormField(
controller: _nameController, controller: _nameController,
@@ -193,43 +147,19 @@ class _ProfileScreenState extends State<ProfileScreen> {
), ),
), ),
const SizedBox(height: 20.0), const SizedBox(height: 20.0),
BirthDatePicker( BirthdayPicker(
onDateSelected: (birthDay) { onDateSelected: (birthDay) {
_birthDateController.text = _birthdayController.text =
DateFormat('dd/MM/yyyy').format(birthDay); DateFormat('dd/MM/yyyy').format(birthDay);
}, },
controller: _birthDateController, controller: _birthdayController,
), ),
const SizedBox(height: 20.0), const SizedBox(height: 20.0),
GenderDropdown(onChanged: (selectedGender) { GenderDropdown(onChanged: (selectedGender) {
_genderController.text = selectedGender; _genderController.text = selectedGender;
}), }),
ElevatedButton( const SizedBox(height: 60.0),
onPressed: () { saveButton(state, context),
context.read<ProfileBloc>().add(
UpdateUserInfo(
userId: state.user!.id,
picture: _imageFile?.path ??
state.user!.picture ??
'',
name: _nameController.text.isEmpty
? null
: _nameController.text,
nickname:
_nameController.text.trim().toLowerCase(),
email: _emailController.text.isEmpty
? null
: _emailController.text,
phone: _phoneController.text.isEmpty
? null
: _phoneController.text,
birthDate: _birthDateController.text,
gender: _genderController.text,
),
);
},
child: const Text('Guardar'),
),
], ],
), ),
), ),
@@ -241,4 +171,118 @@ class _ProfileScreenState extends State<ProfileScreen> {
), ),
); );
} }
Widget saveButton(MyUserState state, BuildContext context) {
return ElevatedButton(
onPressed: () {
if (isLoading) {
return;
}
final myUser = state.user!.copyWith(
name: _nameController.text,
email: _emailController.text,
phone: _phoneController.text,
birthday: _birthdayController.text,
gender: _genderController.text,
nickname: _nameController.text.trim().toLowerCase(),
);
context.read<ProfileBloc>().add(
UpdateUserInfo(
myUser: myUser,
filePicture: _imageFile?.path,
),
);
// Navigator.pop(context);
},
style: ElevatedButton.styleFrom(
backgroundColor: Colors.blue, // Color de fondo
padding: const EdgeInsets.symmetric(vertical: 15),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20), // Radio de borde
),
shadowColor: Colors.grey, // Sombra
elevation: 5, // Elevación
),
child: Container(
constraints: const BoxConstraints(
maxWidth: 300.0, minHeight: 50.0), // Ajustes de tamaño
alignment: Alignment.center,
child: isLoading
? const CircularProgressIndicator(
color: Colors.white,
)
: const Text(
'Actualizar',
style: TextStyle(
color: Colors.white,
fontSize: 18,
fontWeight: FontWeight.bold, // Texto audaz
),
),
),
);
}
Widget pictureWidget(MyUserState state, BuildContext context) {
final pictureUrl = state.user?.picture;
final pathImageFile = _imageFile?.path;
ImageProvider<Object>? imageProvider;
if (pathImageFile != null && pathImageFile.isNotEmpty) {
imageProvider = FileImage(File(pathImageFile));
} else if (pictureUrl != null && pictureUrl.isNotEmpty) {
imageProvider = NetworkImage(pictureUrl);
}
return GestureDetector(
onTap: () async {
final ImagePicker picker = ImagePicker();
final XFile? image = await picker.pickImage(
source: ImageSource.gallery,
maxHeight: 500,
maxWidth: 500,
imageQuality: 40,
);
if (image != null) {
setState(() {
_imageFile = image;
});
}
},
child: pictureContainerWidget(imageProvider),
);
}
Widget pictureContainerWidget(ImageProvider<Object>? imageProvider) {
final image = imageProvider == null
? null
: DecorationImage(
image: imageProvider,
fit: BoxFit.contain,
);
final widget = image == null
? Icon(
CupertinoIcons.person,
color: Colors.grey.shade400,
size: 40,
)
: null;
return Container(
width: 120,
height: 120,
decoration: BoxDecoration(
color: Colors.grey.shade300,
shape: BoxShape.circle,
image: image,
),
child: widget,
);
}
} }
@@ -210,16 +210,16 @@ class AuthenticationRepository extends GetxController {
} }
Future<String> getBirthday(String uid) async { Future<String> getBirthday(String uid) async {
String birthDate = ''; String birthday = '';
try { try {
final snapshot = final snapshot =
await FirebaseFirestore.instance.collection('users').doc(uid).get(); await FirebaseFirestore.instance.collection('users').doc(uid).get();
final Map<String, dynamic>? data = snapshot.data(); final Map<String, dynamic>? data = snapshot.data();
birthDate = data?['birth_date'] ?? ''; birthday = data?['birth_date'] ?? '';
} catch (e) { } catch (e) {
print('Error getting birthDate: $e'); print('Error getting birthday: $e');
} }
return birthDate; return birthday;
} }
Future<String> getCoordsOfCity(String uid) async { Future<String> getCoordsOfCity(String uid) async {
@@ -7,14 +7,18 @@ class MyUserEntity extends Equatable {
final String? name; final String? name;
final String? nickname; final String? nickname;
final String? picture; final String? picture;
final String? birthday;
final String? gender;
const MyUserEntity({ const MyUserEntity({
required this.id, required this.id,
this.email, required this.email,
this.phone, required this.phone,
this.name, required this.name,
this.nickname, required this.nickname,
this.picture, required this.picture,
required this.birthday,
required this.gender,
}); });
Map<String, Object?> toDocument() { Map<String, Object?> toDocument() {
@@ -25,6 +29,8 @@ class MyUserEntity extends Equatable {
'name': name, 'name': name,
'nickname': name?.trim().toLowerCase(), 'nickname': name?.trim().toLowerCase(),
'picture': picture, 'picture': picture,
'birthday': birthday,
'gender': gender,
}; };
} }
@@ -36,11 +42,14 @@ class MyUserEntity extends Equatable {
name: doc['name'] as String?, name: doc['name'] as String?,
nickname: doc['nickname'] as String?, nickname: doc['nickname'] as String?,
picture: doc['picture'] as String?, picture: doc['picture'] as String?,
birthday: doc['birthday'] as String?,
gender: doc['gender'] as String?,
); );
} }
@override @override
List<Object?> get props => [id, email, phone, name, nickname, picture]; List<Object?> get props =>
[id, email, phone, name, nickname, picture, birthday, gender];
@override @override
String toString() { String toString() {
@@ -51,6 +60,8 @@ class MyUserEntity extends Equatable {
name: $name name: $name
nickname: $nickname nickname: $nickname
picture: $picture picture: $picture
birthday: $birthday
gender: $gender
}'''; }''';
} }
} }
@@ -9,6 +9,8 @@ class MyUser extends Equatable {
final String? name; final String? name;
final String? nickname; final String? nickname;
final String? picture; final String? picture;
final String? birthday;
final String? gender;
const MyUser({ const MyUser({
required this.id, required this.id,
@@ -17,8 +19,16 @@ class MyUser extends Equatable {
this.name, this.name,
this.nickname, this.nickname,
this.picture, this.picture,
this.birthday,
this.gender,
}); });
get drawerLabel => email != null && email!.isNotEmpty
? email!
: phone != null && phone!.isNotEmpty
? phone!
: "N/A";
/// Empty user which represents an unauthenticated user. /// Empty user which represents an unauthenticated user.
static const empty = MyUser( static const empty = MyUser(
id: '', id: '',
@@ -27,6 +37,8 @@ class MyUser extends Equatable {
name: '', name: '',
nickname: '', nickname: '',
picture: '', picture: '',
birthday: '',
gender: '',
); );
/// Modify MyUser parameters /// Modify MyUser parameters
@@ -37,6 +49,8 @@ class MyUser extends Equatable {
String? name, String? name,
String? nickname, String? nickname,
String? picture, String? picture,
String? birthday,
String? gender,
}) { }) {
return MyUser( return MyUser(
id: id ?? this.id, id: id ?? this.id,
@@ -45,6 +59,8 @@ class MyUser extends Equatable {
name: name ?? this.name, name: name ?? this.name,
nickname: nickname ?? this.nickname, nickname: nickname ?? this.nickname,
picture: picture ?? this.picture, picture: picture ?? this.picture,
birthday: birthday ?? this.birthday,
gender: gender ?? this.gender,
); );
} }
@@ -62,6 +78,8 @@ class MyUser extends Equatable {
name: name, name: name,
nickname: nickname, nickname: nickname,
picture: picture, picture: picture,
birthday: birthday,
gender: gender,
); );
} }
@@ -73,9 +91,12 @@ class MyUser extends Equatable {
name: entity.name, name: entity.name,
nickname: entity.nickname, nickname: entity.nickname,
picture: entity.picture, picture: entity.picture,
birthday: entity.birthday,
gender: entity.gender,
); );
} }
@override @override
List<Object?> get props => [id, email, phone, name, nickname, picture]; List<Object?> get props =>
[id, email, phone, name, nickname, picture, birthday, gender];
} }
@@ -218,25 +218,12 @@ class FirebaseUserRepository implements UserRepository {
} }
@override @override
Future<void> updateUserInfo( Future<void> updateUserInfo(MyUser myUser) async {
String userId, String? picture, Map<String, dynamic> data) async {
try { try {
if (picture != null) { await usersCollection
File imageFile = File(picture); .doc(myUser.id)
Reference firebaseStoreRef = .update(myUser.toEntity().toDocument());
FirebaseStorage.instance.ref().child('$userId/PP/${userId}_lead'); await updateFromFirebase(myUser.id);
await firebaseStoreRef.putFile(
imageFile,
);
String url = await firebaseStoreRef.getDownloadURL();
await usersCollection.doc(userId).update({'picture': url});
}
await usersCollection.doc(userId).update(data);
await updateFromFirebase(userId);
} catch (e) { } catch (e) {
log(e.toString()); log(e.toString());
rethrow; rethrow;
@@ -249,11 +236,8 @@ class FirebaseUserRepository implements UserRepository {
File imageFile = File(file); File imageFile = File(file);
Reference firebaseStoreRef = Reference firebaseStoreRef =
FirebaseStorage.instance.ref().child('$userId/PP/${userId}_lead'); FirebaseStorage.instance.ref().child('$userId/PP/${userId}_lead');
await firebaseStoreRef.putFile( await firebaseStoreRef.putFile(imageFile);
imageFile,
);
String url = await firebaseStoreRef.getDownloadURL(); String url = await firebaseStoreRef.getDownloadURL();
await usersCollection.doc(userId).update({'picture': url});
return url; return url;
} catch (e) { } catch (e) {
log(e.toString()); log(e.toString());
@@ -22,8 +22,7 @@ abstract class UserRepository {
Future<MyUser?> getMyUser(String myUserId); Future<MyUser?> getMyUser(String myUserId);
Future<void> updateUserInfo( Future<void> updateUserInfo(MyUser myUser);
String userId, String picture, Map<String, dynamic> data);
Future<String> uploadPicture(String file, String userId); Future<String> uploadPicture(String file, String userId);