Home > Mobile >  Flutter How to validate uniqe username?
Flutter How to validate uniqe username?

Time:12-21

I am trying to validate uniqe username for SignUp Page.

Here is my TextFormField code:

TextFormField(
                          onSaved: (deger) => _username = deger!,
                          textInputAction: TextInputAction.done,
                          keyboardType: TextInputType.name,
                          controller: usernameController,
                          decoration: const InputDecoration(
                            suffixIcon: Icon(Icons.person),
                            label: Text("username"),
                          ),
                        ),

Here is my Button:

ElevatedButton(
                                onPressed: () async {
                                  final valid = await _checkUserName(
                                      usernameController.text);
                                  if (valid!) {
                                
                                    Get.snackbar(
                                        "hata", "username exist");
                                  } else if (formKey.currentState!.validate()) {
                               
                                     formKey.currentState!.save();
                                    //myAuthController codes here it doesnt metter.
                                    
                                  } else {
                                    debugPrint("error");
                                  }
                                },
                                child: const Text("SIGNUP"),
                              ),

My function for validate existed username in Firestore:

Future<bool?> _checkKullaniciAdi(String username) async {
    final result = await FirebaseFirestore.instance
        .collection("customer")
        .where('username', isEqualTo: username)
        .get();
    return result.docs.isEmpty;
  }

This codes are always returning

 Get.snackbar("hata", "username exist");

What can I do ?

CodePudding user response:

if (valid!) {
  Get.snackbar("hata", "username exist");
}

if the username is valid, show hata username exists

That's what the above code says. This is more likely what you wanted:

if (!valid!) {
  Get.snackbar("hata", "username exist");
}

The first ! means not, so if it is not valid, the second ! means that valid can't be null, if valid is null, it will throw an error.

Finally, the reason why we have to add the second ! is because your _checkKullaniciAdi method returns bool? so it can return true, false or null. But it doesn't return null, you marked it as a possibility, but it never happens, you could change the return type to Future<bool> and that way you would be able to remove the second !

Future<bool> _checkKullaniciAdi(String username) {
}
if (!valid) {

}
  • Related