简体   繁体   中英

Flutter check if username already exist in Firestore database

In my App I have to implement a SignUpScreen.

注册屏幕

Everything works fine but one thing not. When someone wants to sign up he cannot use the same email like a other users, this works, but I want also that he cannot use the same username. I have a collection which is called 'SerX' and a document field which is called 'Username:' in cloud firestore. If anyone knows how to do that please comment your solution.

There should be a return like this return 'This username already exists;';

Widget _buildUserNameTF()  {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        Text(
          'Username',
          style: kLabelStyle,
        ),
        SizedBox(height: 10.0),
        Container(
          alignment: Alignment.centerLeft,
          decoration: kBoxDecorationStyle,
          height: 60.0,
          child: TextFormField(
            keyboardType: TextInputType.text,
            validator: (input) {
              if (input.isEmpty) {
                return 'Please enter a username';
              }

              if(input.length < 6){
                return 'Your username needs to be at least 6 characters';
              }else if(input.length > 12){
                return 'Your username needs to be at most 12 characters';
              }

              if (!RegExp(
                  r'^[a-zA-Z0-9]+$')
                  .hasMatch(input)) {
                return 'Please enter a valid username.';
              }


            },
            onSaved: (input) => _Username = input,
            style: TextStyle(
              color: Colors.black,
              fontFamily: 'Orbitron',
            ),
            decoration: InputDecoration(
              border: InputBorder.none,
              contentPadding: EdgeInsets.only(top: 14.0),
              prefixIcon: Icon(
                Icons.supervised_user_circle,
                color: Colors.black,
              ),
              hintText: 'Enter your Username',
              hintStyle: kHintTextStyle,
            ),
          ),
        ),
      ],
    );
  }

Here is a simple function for checking if the username is already exists on client side.

  var _instance = Firestore.instance;

  Future<bool> userExists(String username) async =>
      (await _instance.collection("users").where("username", isEqualTo: username).getDocuments()).documents.length > 0;

Client side check is not a secure solution. You should use Cloud Functions for Firebase for it.

I don't know if it is the perfect solution but it works for me.

doesUserExist(currentUserName) async {
    try {
// if the size of value is greater then 0 then that doc exist. 
      await FirebaseFirestore.instance
          .collection('Users')
          .where('email', isEqualTo: currentEmail)
          .get()
          .then((value) => value.size > 0 ? true : false);
    } catch (e) {
      debugPrint(e.toString());
     
    }
  }
var formKey = GlobalKey<FormState>();
var username = TextEditingController();
var password = TextEditingController();

Future<bool> userExists(username , password) async {
    return await FirebaseFirestore.instance.collection('users')
          .where('username', isEqualTo: username)
          .where('password', isEqualTo: password)
          .get()
          .then((value) => value.size > 0 ? true : false);
}

login() async {
   bool result = await userExists(username.text.toString(), 
   password.text.toString());
   
  // ignore: unrelated_type_equality_checks
   if(result == true){
      Navigator.push(
        context, MaterialPageRoute(builder: (context) => Home()));
   }else{
     password.text = '';
     Fluttertoast.showToast(msg: "Incorrect Username or Password", toastLength: 
     Toast.LENGTH_LONG);
   }
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM