LoginSignup
0
0

【Flutter】Firebase Authenticationを使ってログイン/ユーザー登録画面を作成する(その4)

Last updated at Posted at 2024-01-18

はじめに

【Flutter】Firebase Authenticationを使ってログイン/ユーザー登録画面を作成する(その3)の続きです。
前回はメールアドレスでのユーザー登録の実装を行いました。
今回はログイン画面を作成し、ログインできるように実装します。
引き続きVSCodeのMac版を利用していますので、AndroidStudio利用の方は適宜読み替えて行ってみてください。

更新履歴

2024.1.18 初回投稿

ログインボタンを追加してログイン処理を実装

  • 前回のコードにログインボタンとログアウトボタンを追加します。
       SizedBox(
        width: double.infinity,
        // ログインボタン
        child: ElevatedButton(
          child: const Text('ログイン'),
          onPressed: () async {
            try {
              // メール/パスワードでログイン
              final FirebaseAuth auth = FirebaseAuth.instance;
              await auth.signInWithEmailAndPassword(
                email: email,
                password: password,
              );
              // ユーザー登録に成功した場合
              setState(() {
                infoText = "ログインに成功しました!";
              });
            } catch (e) {
              // ユーザー登録に失敗した場合
              setState(() {
                infoText = "ログインに失敗しました:${e.toString()}";
              });
            }
          },
        ),
      ),
    

ログアウトボタンを追加してログアウト処理を実装

  • 次にログアウトボタンを追加して、ログアウト処理を追加します。
       SizedBox(
        width: double.infinity,
        // ログアウトボタン
        child: ElevatedButton(
          child: const Text('ログアウト'),
          onPressed: () async {
            try {
              // ログアウト
              await FirebaseAuth.instance.signOut();
              // ユーザー登録に成功した場合
              setState(() {
                infoText = "ログアウトしました";
              });
            } catch (e) {
              // ユーザー登録に失敗した場合
              setState(() {
                infoText = "ログアウトに失敗しました:${e.toString()}";
              });
            }
          },
        ),
      ),
    

ここまでの全コード

    import 'package:flutter/material.dart';
    import 'package:firebase_auth/firebase_auth.dart';
    import 'package:firebase_core/firebase_core.dart';
    import 'firebase_options.dart';
    
    void main() async {
      WidgetsFlutterBinding.ensureInitialized();
      await Firebase.initializeApp(
        options: DefaultFirebaseOptions.currentPlatform,
      );
      runApp(const LoginSample());
    }
    
    class LoginSample extends StatelessWidget {
      const LoginSample({super.key});
    
      @override
      Widget build(BuildContext context) {
        return const MaterialApp(
          title: 'Login Sample',
          home: LoginPage(),
        );
      }
    }
    
    class LoginPage extends StatefulWidget {
      const LoginPage({super.key});
    
      @override
      State<LoginPage> createState() => _LoginPageState();
    }
    
    class _LoginPageState extends State<LoginPage> {
      // メッセージ表示用
      String infoText = '';
      // 入力したメールアドレス・パスワード
      String email = '';
      String password = '';
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: Center(
            child: Container(
              padding: const EdgeInsets.all(24),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  // メールアドレス入力
                  TextFormField(
                    decoration: const InputDecoration(labelText: 'メールアドレス'),
                    onChanged: (String value) {
                      setState(() {
                        email = value;
                      });
                    },
                  ),
                  // パスワード入力
                  TextFormField(
                    decoration: const InputDecoration(labelText: 'パスワード'),
                    obscureText: true,
                    onChanged: (String value) {
                      setState(() {
                        password = value;
                      });
                    },
                  ),
                  Container(
                    padding: const EdgeInsets.all(8),
                    // メッセージ表示
                    child: Text(infoText),
                  ),
                  SizedBox(
                    width: double.infinity,
                    // ユーザー登録ボタン
                    child: ElevatedButton(
                      child: const Text('ユーザー登録'),
                      onPressed: () async {
                        try {
                          // メール/パスワードでユーザー登録
                          final FirebaseAuth auth = FirebaseAuth.instance;
                          await auth.createUserWithEmailAndPassword(
                            email: email,
                            password: password,
                          );
                          // ユーザー登録に成功した場合
                          setState(() {
                            infoText = "登録に成功しました!";
                          });
                        } catch (e) {
                          // ユーザー登録に失敗した場合
                          setState(() {
                            infoText = "登録に失敗しました:${e.toString()}";
                          });
                        }
                      },
                    ),
                  ),
                  SizedBox(
                    width: double.infinity,
                    // ログインボタン
                    child: ElevatedButton(
                      child: const Text('ログイン'),
                      onPressed: () async {
                        try {
                          // メール/パスワードでログイン
                          final FirebaseAuth auth = FirebaseAuth.instance;
                          await auth.signInWithEmailAndPassword(
                            email: email,
                            password: password,
                          );
                          // ユーザー登録に成功した場合
                          setState(() {
                            infoText = "ログインに成功しました!";
                          });
                        } catch (e) {
                          // ユーザー登録に失敗した場合
                          setState(() {
                            infoText = "ログインに失敗しました:${e.toString()}";
                          });
                        }
                      },
                    ),
                  ),
                  SizedBox(
                    width: double.infinity,
                    // ログアウトボタン
                    child: ElevatedButton(
                      child: const Text('ログアウト'),
                      onPressed: () async {
                        try {
                          // ログアウト
                          await FirebaseAuth.instance.signOut();
                          // ユーザー登録に成功した場合
                          setState(() {
                            infoText = "ログアウトしました";
                          });
                        } catch (e) {
                          // ユーザー登録に失敗した場合
                          setState(() {
                            infoText = "ログアウトに失敗しました:${e.toString()}";
                          });
                        }
                      },
                    ),
                  ),
                ],
              ),
            ),
          ),
        );
      }
    }

次は、パスワードリセットを実装していきたいと思います。

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