Edo Sagron
 · Flutter Developer

Change User Password [Firebase] [Email + Password Auth]

Hello everyone 😁

I'm sure this is somethign a lot of people will find useful!
When a user wants to change their password, the default option in FF is to send a reset link to their email, so I created a custom action to change the password instead!

import 'package:firebase_auth/firebase_auth.dart';

Future<String> changePassword(
    String currentPassword, String newPassword, String email) async {
  try {
    User? user = FirebaseAuth.instance.currentUser;

    // Reauthenticate the user.
    AuthCredential credential = EmailAuthProvider.credential(
      email: email,
      password: currentPassword,
    );
    await user?.reauthenticateWithCredential(credential);

    // If reauthentication is successful, change the password.
    await user?.updatePassword(newPassword);

    // Password changed successfully.
    return 'Password changed successfully.';
  } catch (e) {
    // Handle reauthentication errors and password change errors.
    return 'Error changing password: $e';
  }
}

As you can see, the action accepts 3 parameters:

  • email - the authenticated user's email.

  • currentPassword - from a field you'll put on the "change password" page / component.

  • newPassword - the new password the user chooses.

The return value is a string which states if the operation was a success or an error which can be displayed in a snackbar or however you see fit.

This is specifically for the Email & Password authentication.

I hope you found this useful!

27
13 replies