I'm trying to create a unique username for each user on my app. At sign up, I'm storing that username value in a separate collection ('Usernames') so it's easier to go through them when I check if the username is unique, instead of going through each user and their fields.
On my signup.dart I have a text field validator:
TextFormField(
style: TextStyle(fontSize: 16.0, color: Colors.white),
decoration: buildSignInInputDecoration("Username"),
validator: (value) {
if (value.length < 2 || value.isEmpty) {
return "Username is too short.";
} else if (value.length > 12) {
return "Username is too long.";
} else {
return null;
},
onSaved: (value) => _username = value.trim(),
),
}
And I made a function to check if username is already in the collection: (_username is the string that stores user input)
Future<bool> usernameCheck() async {
final snapShot = await usernamesRef.document(_username).get();
if (snapShot == null || !snapShot.exists) {
return true; //username is unique.
} else {
return false; //username exists.
}
}
My question is, how can I call usernameCheck and validate it with my validator? Thanks in advance!
UPDATE: I implemented the answer given bellow, but somehow valid always returns false, even if the username doesn't exist.
Future<bool> usernameCheck(String _username) async {
final result =
await usersRef.where("username", isEqualTo: _username).getDocuments();
return result.documents.isEmpty;
}
//Gets called on sign up button pressed.
Future<void> validateAndSubmit() async {
final valid = await usernameCheck(_username);
if (!valid) {
print("Username Exists.");
} else if (validateAndSave()) {
try {
// Signs up and save data.