createUserWithEmailAndPassword method

Future<UserCredential> createUserWithEmailAndPassword({
  1. required String email,
  2. required String password,
  3. String? displayName,
})

Creates a new user with the provided email, password, and optional display name, and returns the user credential.

Implementation

Future<UserCredential> createUserWithEmailAndPassword({
  required String email,
  required String password,
  String? displayName,
}) async {
  try {
    // Sign out current user if not anonymous
    if (_auth.currentUser != null && _auth.currentUser!.isAnonymous != true) {
      await _auth.signOut();
    } else if (_auth.currentUser != null &&
        _auth.currentUser!.isAnonymous == true) {
      /// create email provider
      final emailProvider =
          EmailAuthProvider.credential(email: email, password: password);
      final credential =
          await _auth.currentUser!.linkWithCredential(emailProvider);
      if (displayName is String && displayName.isNotEmpty) {
        await credential.user?.updateDisplayName(displayName);
      }
      //This should update claims too
      await resendEmailVerification(email);
      await _auth.currentUser!.reload();
      return credential;
    }

    final credential = await _auth.createUserWithEmailAndPassword(
        email: email, password: password);
    if (displayName is String && displayName.isNotEmpty) {
      await credential.user?.updateDisplayName(displayName);
    }

    return credential;
  } catch (err) {
    if (err is FirebaseAuthException) {
      throw AuthDataServiceException.fromRdevException(err.toRdevException());
    }
    throw AuthDataServiceException(
      message: err.toString(),
    );
  }
}