0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Flutter × FirebaseAuthで認証機能を実装する(新規登録・ログイン・ログアウト)

0
Posted at

Flutterアプリでユーザー認証を実装する場合、Firebase Authenticationを使うと簡単に実装できます。

前提

以下が完了している前提で進めます。

  • Firebaseプロジェクト作成済み
  • FlutterアプリとFirebaseの連携済み
  • email/password認証を有効化済み

使用パッケージ

dependencies:
  firebase_auth: ^6.4.0

新規会員登録

Future<void> signUp(String email, String password) async {
  await FirebaseAuth.instance.createUserWithEmailAndPassword(
    email: email,
    password: password,
  );
}

ログイン

Future<void> signIn(String email, String password) async {
  await FirebaseAuth.instance.signInWithEmailAndPassword(
    email: email,
    password: password,
  );
}

ログアウト

Future<void> signOut() async {
  await FirebaseAuth.instance.signOut();
}

ログイン状態で画面を出し分ける

StreamBuilder<User?>(
  stream: FirebaseAuth.instance.authStateChanges(),
  builder: (context, snapshot) {
    // ローディング中
    if (snapshot.connectionState == ConnectionState.waiting) {
      return const Center(child: CircularProgressIndicator());
    }

    // ログイン済み
    if (snapshot.hasData) {
      return const HomePage();
    }

    // 未ログイン
    return const LoginPage();
  },
)

authStateChangesはログイン・ログアウトなどの状態変化を監視するストリームです。

これを使うことで、

ログイン済み → ホーム画面
未ログイン → ログイン画面

といった自動遷移が実現できます。

少ないコードで認証が実装できました。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?