Flutter + firebase authentication ログイン機能

NO IMAGE

flutterアプリにfirebase authenticationを使ってログイン機能を作成する時の方法について、本ページで記載します。

firebase authenticationを使うにはまず別のページで紹介している初期設定が必要になります。

そちらの設定がまだの方はまずページを参照し初期設定を行ってください。

Firebase authentication実装

1. firebase authenticationパッケージを導入

flutterアプリのpubspec.yaml(プロジェクトフォルダ直下)に「firebase_auth: ^0.18.2」を追加します。

dependencies:
  flutter:
    sdk: flutter

  cupertino_icons: ^0.1.2
  firebase_core: ^0.5.1
  firebase_auth: ^0.18.2 

^0.18.2は記事を書いている時点の最新のバージョンなので「https://pub.dev/」のサイトでfirebase_authと調べて最新バージョンを確認してみてください。

2. firebase_authenticationをimport

firebase_authenticationのパッケージをソースにimportします。

対象のソースで下記のimport文を記載してください

import 'package:firebase_auth/firebase_auth.dart';

3. firebase_authのインスタンスを生成

FirebaseAuth.instanceでインスタンスが生成できます。

ログインの画面で下記のようにインスタンスを生成します。

class _LoginScreenState extends State<LoginScreen> {
  final _auth = FirebaseAuth.instance;
  String email;
  String password;
  @override
  Widget build(BuildContext context) {

4. Firebaseへのユーザログイン

email変数とpassword変数に登録するユーザのemailアドレス、passwordが格納されているという前提で

ユーザログイン時にクリックするログインボタンのonPressedメソッドに下記のようなコードを記載します。

onPressed: () async {
                try {
                  final user = await _auth.signInWithEmailAndPassword(
                      email: email, password: password);
                  if (user != null) {
                    Navigator.pushNamed(context, "ログイン後に遷移する画面");
                  }
                } catch (e) {
                  print(e);
                }
              },

3で作成したfirebase authenticationのインスタンスの.signInWithEmailAndPassword(
email: email, password: password);メソッドを呼ぶことで登録済みのユーザであった場合は、user情報が帰ってきます。

Firebaseカテゴリの最新記事