Skip to content

Instantly share code, notes, and snippets.

@prajwal27
Last active June 17, 2021 18:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save prajwal27/0476bec7201965788c8d91c45bd70607 to your computer and use it in GitHub Desktop.
Save prajwal27/0476bec7201965788c8d91c45bd70607 to your computer and use it in GitHub Desktop.
Instagram like Follow-Unfollow feature
Future<void> followUser(String userId, String username) async {
var batch = firebaseFirestore.batch();
var myDocument = firebaseFirestore
.collection('Users')
.doc(firebaseAuth.currentUser!.uid);
var myFDocument = firebaseFirestore
.collection('Follow')
.doc(firebaseAuth.currentUser!.uid);
var myFollowingDocument = firebaseFirestore
.collection('Users')
.doc(firebaseAuth.currentUser!.uid)
.collection("Following")
.doc(userId);
batch.update(myDocument, {"following": FieldValue.increment(1)});
batch.set<Map<String, dynamic>>(
myFDocument,
{
'following': FieldValue.arrayUnion(
[
{
'userId': userId,
'username': username,
}
],
)
},
SetOptions(merge: true));
batch.set<Map<String, dynamic>>(
myFollowingDocument,
followingJSON(FollowStatus.sent, userModel!.username),
SetOptions(merge: true));
// OTHER USER
var otherDocument = firebaseFirestore.collection('Users').doc(userId);
var otherFDocument = firebaseFirestore.collection('Follow').doc(userId);
var othersFollowersDocument = firebaseFirestore
.collection('Users')
.doc(userId)
.collection("Followers")
.doc(firebaseAuth.currentUser!.uid);
batch.update(otherDocument, {"followers": FieldValue.increment(1)});
batch.set<Map<String, dynamic>>(
otherFDocument,
{
'followers': FieldValue.arrayUnion(
[
{
'userId': firebaseAuth.currentUser!.uid,
'username': currentUserModel.username,
}
],
)
},
SetOptions(merge: true));
batch.set<Map<String, dynamic>>(
othersFollowersDocument,
followingJSON(FollowStatus.pending, userModel!.username),
SetOptions(merge: true));
await batch.commit();
}
Map<String, dynamic> followingJSON(FollowStatus status, String username) {
return {
"status": status,
"requesterUsername": username,
"modifiedDate": DateTime.now(),
};
}
Map<String, dynamic> followerSON(FollowStatus status, String username) {
return {
"status": status,
"requesterUsername": username,
"modifiedDate": DateTime.now(),
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment