removeFriendship method
- String userEmail,
- String otherUserName,
- BuildContext context
Removes a friendship or cancels a friend request.
Displays appropriate success or error messages.
Implementation
Future<void> removeFriendship(String userEmail, String otherUserName, BuildContext context) async {
final errorTitle = AppLocalizations.of(context)?.tError ?? "Error";
final noUserFoundMessage = AppLocalizations.of(context)?.tNoUserFound ?? "User not found";
final successTitle = AppLocalizations.of(context)?.tSuccess ?? "Success";
final infoTitle = AppLocalizations.of(context)?.tInfo ?? "Info";
final friendDeletedMessage = AppLocalizations.of(context)?.tFriendDeleted ?? "was removed from your friends";
final friendshipRequestWithdraw = AppLocalizations.of(context)?.tFriendshipRequestWithdraw ?? "Friend request withdrawn from";
final friendDeleteException = AppLocalizations.of(context)?.tFriendDeleteException ?? "Error removing friend";
final usersRef = FirebaseFirestore.instance.collection('users');
final userQuery = await usersRef.where('email', isEqualTo: userEmail).get();
final otherUserQuery =
await usersRef.where('username', isEqualTo: otherUserName).get();
if (userQuery.docs.isEmpty || otherUserQuery.docs.isEmpty) {
Helper.errorSnackBar(
title: errorTitle,
message: noUserFoundMessage,
);
return;
}
final userRef = userQuery.docs.first.reference;
final otherUserRef = otherUserQuery.docs.first.reference;
try {
final friendships = await FirebaseFirestore.instance
.collection('friendships')
.where(Filter.or(
Filter.and(Filter('sender', isEqualTo: userRef),
Filter('receiver', isEqualTo: otherUserRef)),
Filter.and(Filter('sender', isEqualTo: otherUserRef),
Filter('receiver', isEqualTo: userRef)),
))
.get();
if (friendships.docs.isEmpty) {
throw Exception("No friendship found");
}
bool isPending = false;
for (var doc in friendships.docs) {
final status = doc.get('status');
if (status == 'pending') {
isPending = true;
break;
}
}
for (var doc in friendships.docs) {
await doc.reference.delete();
}
friends.removeWhere((friend) =>
friend['username'] == otherUserName ||
(friend['email'] != null && friend['email'] == otherUserName)
);
if (isPending) {
Helper.warningSnackBar(
title: infoTitle,
message: friendshipRequestWithdraw + otherUserName,
);
} else {
Helper.successSnackBar(
title: successTitle,
message: '$otherUserName $friendDeletedMessage',
);
}
} catch (e) {
Helper.errorSnackBar(
title: errorTitle,
message: friendDeleteException,
);
rethrow;
}
}