How to validate Unique username to all users in Flutter social media app?

Issue

I am creating a Memer social media app. So in this everything is ready but I am confused in providing Unique display name for all users. User name are given by users. But how to validate that it is really present or not? All data are stored in firebase cloud firestore. So can anybody can help me?
Username is stored is like this: collection "users" -> document "userId" ->field "username"

Solution

For this I made a new collection with the name username. And before creating the account i was calling this function to check availability:-

checkUsernameIsUnique(String username)async
  {
    QuerySnapshot querySnapshot;
    setState(() {
      loading=true;
    });
    querySnapshot=await FirebaseFirestore.instance.collection('username').where("username",isEqualTo: username).getDocuments();
    print(querySnapshot.documents.isNotEmpty);
    return querySnapshot.documents.isEmpty;
  }

checkUsernameIsUnique('username to be checked').then((val){
if(val)
{
   //create the user and store the username in username collection also
   FirebaseFirestore.instance.collection('username').document(widget.username).setData({
        "username":widget.username,
      });
}
else 
//username is taken
});

Answered By – Deepak Lohmod

Answer Checked By – Cary Denson (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *