2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Flutter】FirebaseAuthで、「パスワードをお忘れの場合」のメールを送る

Last updated at Posted at 2023-07-27

やりたいこと

Flutter×FirebaseAuthでログイン管理をしているアプリで、メール認証のパスワードリセットのメールを送ることができるようにしたいです。
Screenshot_20230728_001818.png

簡単にできました

FirebaseAuthでのログインはできるようになっている前提で、
以下を記載して、引数の "email" に送信先を渡すだけで、簡単にメールを送ることができました。メール送信はFirebaseAuth側で行なってくれるため、この部分だけであれば、メール送信の仕組みを作る必要がなく、パスワードの変更画面も、FirebaseAuthのデフォルトのものがあるので、これだけでパスワードリセットの仕組みができるようです。こちらはユーザーのパスワードを知らなくても良いのもとてもうれしいです。

FirebaseAuth.instance.sendPasswordResetEmail(email: targetEmail);

メール文言を変更する

デフォルトのままですと、英語のデフォルトテンプレートで、メールが送信されてしまいます。
メールの内容をカスタマイズしたい場合は、Firebaseのプロジェクトで、
Authentication > Template > パスワードの再設定
から変更することができます。

エラー処理を行う

存在しないユーザーの場合などの、エラー処理を行います。
パスワードリセットメールのメソッド(sendPasswordResetEmail)で発生するエラーコードの一覧は、こちらにまとまっています。

私の場合は、以下のように、エラーコードによって、エラーメッセージをセットし、この後の部分でダイアログとして表示しています。

///パスワードリセットメール送信
    try {
      await FirebaseAuth.instance.sendPasswordResetEmail(email: targetEmail);
    } on FirebaseAuthException catch (e) {
      if (e.code == 'invalid-email') {
        ///無効なメールアドレス
        errorMessage = ErrorMessageList.inValidEmail;
      } else if (e.code == 'user-not-found') {
        ///ユーザーが存在しない
        errorMessage = ErrorMessageList.userNotFound;
      } else {
        ///その他の失敗
        errorMessage = ErrorMessageList.sendPasswordResetMailFail;
      }
    } on Exception {
      ///その他の失敗
      errorMessage = ErrorMessageList.sendPasswordResetMailFail;
    }

参考にさせていただいたサイト

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?