Last active
June 17, 2021 18:06
-
-
Save prajwal27/0476bec7201965788c8d91c45bd70607 to your computer and use it in GitHub Desktop.
Instagram like Follow-Unfollow feature
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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