今回はFirebaseAuthを使用してメールアドレスとパスワードによるログイン認証を実装する方法を紹介します。
前回の「メールアドレスとパスワード認証による新規登録」の続きとなります。
目次
今回のゴール


createUserWithEmailAndPassword()で登録したメールアドレスとパスワードでログイン認証する機能を実装します。今回は既にFirebaseのAuthenticationにユーザー登録が済んでいる程で解説していきます!
あわせて読みたい


【FlutterFire】メールアドレスとパスワード認証による新規登録
所有時間3分 今回はFirebaseAuthを使用してメールアドレスとパスワードによる新規登録機能を実装する方法を紹介します。 【今回のゴール】 今回は新規登録ページで「メ...
ログイン認証画面を作る
記事下の完成コードで示している「ステップ○」を参考にして読んでみて下さい。
ステップ1:FirebaseAuthをインスタンス化する
//ステップ1
final _auth = FirebaseAuth.instance;
FirebaseAuthをインスタンス化します。
ステップ2:入力されたメールアドレスとパスワードでログイン認証
//ステップ2
onPressed: () async {
try {
final newUser = await _auth.signInWithEmailAndPassword(
email: email, password: password);
if (newUser != null) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const MainContent()),
);
}
} catch (e) {
print(e);
}
}
TextFieldでユーザーから取得したメールアドレスとパスワードをそれぞれsignInWithEmailAndPassword()のemailプロパティ、passwordプロパティに渡します。
ログイン認証で入力したメールアドレスとパスワードが正しい場合(Authenticationで登録済み)はサインインされ、エラーが発生した場合は「FirebaseAuthException」のエラーコードがスローされます。
ステップ2の応用:エラーコード別に実行する処理を指定
- invalid-email
- user-disabled
- user-not-found
- wrong-password
signInWithEmailAndPassword()のエラーは上記の4つだけなのでそれぞれのエラーコードがスローされた場合の処理を指定しておきます。
//ステップ2
onPressed: () async {
try {
final newUser = await _auth.signInWithEmailAndPassword(
email: email, password: password);
if (newUser != null) {
Navigator.pushNamed(context, '/content');
}
} on FirebaseAuthException catch (e) {
if (e.code == 'invalid-email') {
print('メールアドレスのフォーマットが正しくありません');
} else if (e.code == 'user-disabled') {
print('現在指定したメールアドレスは使用できません');
} else if (e.code == 'user-not-found') {
print('指定したメールアドレスは登録されていません');
} else if (e.code == 'wrong-password') {
print('パスワードが間違っています');
}
}
},
これでメールアドレスとパスワードによるログイン認証は完了です。
完成コード
import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_auth/firebase_auth.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(
MaterialApp(
initialRoute: '/userLogin',
routes: {
'/userLogin': (context) => const UserLogin(),
'/content': (context) => const MainContent(),
},
),
);
}
class UserLogin extends StatefulWidget {
const UserLogin({Key? key}) : super(key: key);
@override
_UserLogin createState() => _UserLogin();
}
class _UserLogin extends State<UserLogin> {
//ステップ1
final _auth = FirebaseAuth.instance;
String email = '';
String password = '';
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('ログイン'),
),
body: Column(
children: [
Padding(
padding: const EdgeInsets.all(10.0),
child: TextField(
onChanged: (value) {
email = value;
},
decoration: const InputDecoration(
hintText: 'メールアドレスを入力',
),
),
),
Padding(
padding: const EdgeInsets.all(10.0),
child: TextField(
onChanged: (value) {
password = value;
},
obscureText: true,
decoration: const InputDecoration(
hintText: 'パスワードを入力',
),
),
),
ElevatedButton(
child: const Text('ログイン'),
//ステップ2
onPressed: () async {
try {
final newUser = await _auth.signInWithEmailAndPassword(
email: email, password: password);
if (newUser != null) {
Navigator.pushNamed(context, '/content');
}
} on FirebaseAuthException catch (e) {
if (e.code == 'invalid-email') {
print('メールアドレスのフォーマットが正しくありません');
} else if (e.code == 'user-disabled') {
print('現在指定したメールアドレスは使用できません');
} else if (e.code == 'user-not-found') {
print('指定したメールアドレスは登録されていません');
} else if (e.code == 'wrong-password') {
print('パスワードが間違っています');
}
}
},
)
],
),
);
}
}
class MainContent extends StatefulWidget {
const MainContent({Key? key}) : super(key: key);
@override
_MainContentState createState() => _MainContentState();
}
class _MainContentState extends State<MainContent> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('成功'),
),
body: Center(
child: Text('ログイン成功!'),
),
);
}
}
以上です。
おすすめ記事
あわせて読みたい


【FlutterFire】ログアウトしてトップページに画面遷移させる
今回はFirebaseAuthを使用してログインユーザーをログアウトさせる方法を紹介します。 前回の「メールアドレスとパスワードによるログイン認証」の続きとなります。 【...