First Create a User class.
class UserData { final String userId; final String fullNames; final String email; final String phone; UserData( {this.userId, this.fullNames, this.email, this.phone}); Map<String, dynamic> getDataMap() { return { "userId": userId, "fullNames": fullNames, "email": email, "phone": phone, }; } }
Then you can use a function like this one to save the credentials and save the data to firestore
createOrUpdateUserData(Map<String, dynamic> userDataMap) async { FirebaseUser user = await FirebaseAuth.instance.currentUser(); DocumentReference ref = Firestore.instance.collection('user').document(user.uid); return ref.setData(userDataMap, merge: true); }
==
bool validateAndSave() { final form = _formKey.currentState; if (form.validate()) { form.save(); return true; } return false; } void validateAndSubmit() async { if (validateAndSave()) { try { String userId = _formType == FormType.login ? await widget.auth.signIn(_email, _password)//use your signin : await widget.auth.signUp(_email, _password);//use your signup if (_formType == FormType.register) { UserData userData = new UserData( fullNames: _fullNames, email: _email, phone: "", ); createOrUpdateUserData(userData.getDataMap()); } } catch (e) { setState(() { _isLoading = false; switch (e.code) { case "ERROR_INVALID_EMAIL": _authHint = "Your email address appears to be malformed."; break; case "ERROR_EMAIL_ALREADY_IN_USE": _authHint = "Email address already used in a different account."; break; case "ERROR_WRONG_PASSWORD": _authHint = "Your password is wrong."; break; case "ERROR_USER_NOT_FOUND": _authHint = "User with this email doesn't exist."; break; case "EMAIL NOT VERIFIED": _authHint = "Email not verified: Please go to yor email and verify"; break; case "ERROR_USER_DISABLED": _authHint = "User with this email has been disabled."; break; case "ERROR_TOO_MANY_REQUESTS": _authHint = "Too many Attemps. Account has temporarily disabled.\n Try again later."; break; case "ERROR_OPERATION_NOT_ALLOWED": _authHint = "Signing in with Email and Password is not enabled."; break; case "ERROR_ACCOUNT_EXISTS_WITH_DIFFERENT_CREDENTIAL": _authHint = "The email is in use by another account"; break; default: _authHint = "An undefined Error happened."; } }); print(e); errorDialog(context, _authHint); } } else { setState(() { _authHint = ''; }); }
}
Then use
onpressed:(){ validateAndSubmit(); }
the formtype is an Enum
enum FormType { login, register, reset }
widget.auth.signIn and widget.auth.signUp should be replaced with your signin and signup respectively.
Added a custom error block to differentiate firebase auth errors as well.
Defining an auth page independently will help you reuse your code in future.