FlutterアプリにFirebase Authenticationを導入し、
メールアドレスとパスワードでログインする方法を解説します。
Firebaseとの連携は完了している前提で、
ログイン処理とエラーハンドリングにフォーカスしていきます。
FirebaseAuthの導入
まずは必要なパッケージを追加します。
$ flutter pub add firebase_auth
$ flutter pub add firebase_core
初期化
Firebaseを使用するには、アプリ起動時に初期化が必要です。
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
ログイン方法を指定
FirebaseAuthenticationにてログインプロバイダにメール/パスワードを追加します。
ログイン処理の実装
メールアドレスとパスワードでログインするには、
signInWithEmailAndPasswordを使用します。
try {
await FirebaseAuth.instance.signInWithEmailAndPassword(
email: email,
password: password,
);
debugPrint('ログイン成功');
} on FirebaseAuthException catch (e) {
debugPrint('エラー: ${e.code}');
}
ログインに失敗した場合は、FirebaseAuthExceptionが発生します。
ログイン後の画面遷移
ログイン成功後は画面遷移を行います。
Navigator.pushReplacement(
context,
MaterialPageRoute(builder: (_) => const HomePage()),
);
pushReplacementを使用することで、ログイン画面に戻れないようにできます。
以上で、FlutterでFirebase Authentication(メール/パスワード)ログインの実装は完了です。