getCurrentUser method
Retrieves the current active user.
Optionally accepts plugin options
which allow customizing provider-specific
behavior.
For more information, see the Amplify docs.
Examples
import 'package:amplify_auth_cognito/amplify_auth_cognito.dart';
import 'package:amplify_flutter/amplify_flutter.dart';
Future<String?> getCurrentUserId() async {
try {
final user = await Amplify.Auth.getCurrentUser();
return user.userId;
} on AuthException catch (e) {
safePrint('Could not retrieve current user: ${e.message}');
return null;
}
}
Implementation
@override
Future<CognitoAuthUser> getCurrentUser({
GetCurrentUserOptions? options,
}) async {
final credentialsState = await stateMachine
.acceptAndComplete<CredentialStoreSuccess>(
const CredentialStoreEvent.loadCredentialStore(),
);
final credentials = credentialsState.data;
final signInDetails = credentials.signInDetails;
// Per the `federateToIdentityPool` design, users cannot access user pool
// methods while federated. They must first clear federation to the
// identity pool and then sign into the user pool normally.
if (signInDetails is CognitoSignInDetailsFederated) {
throw const InvalidStateException.federatedToIdentityPool();
}
final tokens = credentials.userPoolTokens;
if (tokens == null || signInDetails == null) {
throw const SignedOutException('No user is currently signed in');
}
final userId = tokens.idToken.userId;
final username = tokens.username;
return CognitoAuthUser(
userId: userId,
username: username,
signInDetails: signInDetails,
);
}