signInAnonymously method

Future<UserCredential> signInAnonymously()

Asynchronously creates and becomes an anonymous user.

If there is already an anonymous user signed in, that user will be returned instead. If there is any other existing user signed in, that user will be signed out.

Important: You must enable Anonymous accounts in the Auth section of the Firebase console before being able to use them.

A FirebaseAuthException maybe thrown with the following error code:

  • operation-not-allowed
    • Thrown if anonymous accounts are not enabled. Enable anonymous accounts in the Firebase Console, under the Auth tab.

Implementation

Future<UserCredential> signInAnonymously() async {
  const providerId = 'anonymous';

  try {
    if (currentUser?.isAnonymous ?? false) {
      return UserCredential._(
        auth: this,
        credential: const AuthCredential(
          providerId: providerId,
          signInMethod: providerId,
        ),
        additionalUserInfo: AdditionalUserInfo(isNewUser: false),
      );
    }

    final response = await _api.signUp.signInAnonymously();
    final userData = await _api.userAccount.getAccountInfo(response.idToken!);

    // Map the json response to an actual user.
    final user = User(userData..addAll(response.toJson()), this);

    _updateCurrentUserAndEvents(user, true);

    return UserCredential._(
        auth: this,
        additionalUserInfo: AdditionalUserInfo(isNewUser: true),
        credential: const AuthCredential(
          providerId: providerId,
          signInMethod: providerId,
        ));
  } catch (e) {
    rethrow;
  }
}