Manage user attributes
Fetch the current user's attributes
Invoke the following api to get the list of attributes assigned to the user.
Future<void> fetchCurrentUserAttributes() async { try { final result = await Amplify.Auth.fetchUserAttributes(); for (final element in result) { print('key: ${element.userAttributeKey}; value: ${element.value}'); } } on AuthException catch (e) { print(e.message); }}
Update user attribute
Invoke the update api for creating new or updating existing user attributes.
To update a single user attribute, call updateUserAttribute
:
Future<void> updateUserAttribute() async { try { final result = await Amplify.Auth.updateUserAttribute( userAttributeKey: CognitoUserAttributeKey.email, value: 'email@email.com', ); if (result.nextStep.updateAttributeStep == 'CONFIRM_ATTRIBUTE_WITH_CODE') { var destination = result.nextStep.codeDeliveryDetails?.destination; print('Confirmation code sent to $destination'); } else { print('Update completed'); } } on AmplifyException catch (e) { print(e.message); }}
To update multiple user attributes at a time, call updateUserAttributes
:
Future<void> updateMultipleUserAttributes() async { const attributes = [ AuthUserAttribute( userAttributeKey: CognitoUserAttributeKey.email, value: 'email@email.com', ), AuthUserAttribute( userAttributeKey: CognitoUserAttributeKey.familyName, value: 'MyFamilyName', ), ];
try { final result = await Amplify.Auth.updateUserAttributes(attributes: attributes); result.forEach((key, value) { if (value.nextStep.updateAttributeStep == 'CONFIRM_ATTRIBUTE_WITH_CODE') { final destination = value.nextStep.codeDeliveryDetails?.destination; print('Confirmation code sent to $destination for $key'); } else { print('Update completed for $key'); } }); } on AmplifyException catch (e) { print(e.message); }}
Verify user attribute
Some attributes require confirmation for the attribute update to complete. If the attribute need to be confirmed, the result of the above api will be CONFIRM_ATTRIBUTE_WITH_CODE
. A confirmation code will be sent to the delivery medium mentioned in the delivery details. When the user gets the confirmation code, you can present a UI to the user to enter the code and invoke the confirm attribute api with their input:
Future<void> verifyAttributeUpdate() async { try { await Amplify.Auth.confirmUserAttribute( userAttributeKey: CognitoUserAttributeKey.email, confirmationCode: '390739', ); print('Attribute verified'); } on AmplifyException catch (e) { print(e.message); }}
Resend verification code
If the code has expired or the user needs to resend the confirmation code, invoke the resend api as shown below:
Future<void> resendVerificationCode() async { try { final result = await Amplify.Auth.resendUserAttributeConfirmationCode( userAttributeKey: CognitoUserAttributeKey.email, ); final destination = result.codeDeliveryDetails.destination; print('Confirmation code set to $destination'); } on AmplifyException catch (e) { print(e.message); }}