앱 개발 공부방

Flutter - firebase 이메일 로그인, 회원가입 본문

FLUTTER

Flutter - firebase 이메일 로그인, 회원가입

춘행이 2022. 3. 22. 13:40
728x90

먼저  프로젝트에서 Authentication 탭을 클릭하고 이메일/비밀번호를  활성화해줍니다

이제 코드로 돌아와 pubspec.yaml에 필요한 것들을 추가해줍니다

firebase_auth: ^3.0.2
firebase_core: ^1.5.0

 

https://pub.dev/packages/firebase_auth

 

firebase_auth | Flutter Package

Flutter plugin for Firebase Auth, enabling Android and iOS authentication using passwords, phone numbers and identity providers like Google, Facebook and Twitter.

pub.dev

 

https://pub.dev/packages/firebase_core

 

firebase_core | Flutter Package

Flutter plugin for Firebase Core, enabling connecting to multiple Firebase apps.

pub.dev

저는 위 두 가지를 추가해줬습니다

 

로그인 화면 login_view.dart

로그인 버튼 코드

GestureDetector(
              onTap: () async {
                try {
                  UserCredential userCredential = await FirebaseAuth.instance
                      .signInWithEmailAndPassword(
                          email: idController.text,
                          password: pwdController.text) //아이디와 비밀번호로 로그인 시도
                      .then((value) {
                    print(value);
                    value.user!.emailVerified == true //이메일 인증 여부
                        ? Navigator.push(context,
                            MaterialPageRoute(builder: (_) => FirstView()))
                        : print('이메일 확인 안댐');
                    return value;
                  });
                } on FirebaseAuthException catch (e) {
                  //로그인 예외처리
                  if (e.code == 'user-not-found') {
                    print('등록되지 않은 이메일입니다');
                  } else if (e.code == 'wrong-password') {
                    print('비밀번호가 틀렸습니다');
                  } else {
                    print(e.code);
                  }
                }
              },
              child: Container(
                child: Center(
                  child: Text(
                    '로그인',
                    style: TextStyle(color: Colors.white),
                  ),
                ),
                width: 100,
                height: 50,
                color: Colors.black,
              )),

FirebaseAuth.instance.signInWithEmailAndPassword()로 로그인 시도해주고 email password 파라미터에 textField에서 입력한 값으로 로그인 시도해줍니다

try catch 문으로 로그인이 실패에 대한 예외처리를 해줍니다

이메일 인증이 완료되면 emailVerified가 true라 true일 때 로그인 완료 페이지인 FirstView로 이동한다

 

회원가입 페이지 

회원 가입 버튼 코드

GestureDetector(
              onTap: () async {
                try {
                  UserCredential userCredential = await FirebaseAuth.instance
                      .createUserWithEmailAndPassword(
                          email: idController.text,
                          password: pwdController.text)
                      .then((value) {
                    if (value.user!.email == null) {
                    } else {
                      Navigator.pop(context);
                    }
                    return value;
                  });
                  FirebaseAuth.instance.currentUser?.sendEmailVerification();
                } on FirebaseAuthException catch (e) {
                  if (e.code == 'weak-password') {
                    print('the password provided is too weak');
                  } else if (e.code == 'email-already-in-use') {
                    print('The account already exists for that email.');
                  } else {
                    print('11111');
                  }
                } catch (e) {
                  print('끝');
                }
              },
              child: Container(
                width: 328,
                height: 48,
                color: Colors.amber,
                child: Center(child: Text('회원가입')),
              ))

FirebaseAuth.instance.createUserWithEmailAndPassword()로 회원가입을 시도하고 email password 파라미터로 이메일과 비밀번호를 입력한다 

등록이 되면 value.user! 에 정보가 있으므로 value.user!. email==null로 등록이 됐느지 안됬는지 확인해주고 등록되었으면 뒤 화면으로 이동하고 입력한 이메일로 인증 이메일을 보낸다

try catch로 비밀번호가 약하거나 이미 있는 계정들을 확인하는 예외처리를 해준다

 

로그인 완료 페이지

FirebaseAuth auth = FirebaseAuth.instance;
Text(auth.currentUser!.email.toString())

현재 로그인한 사용자의 정보를 뿌려준다

728x90

'FLUTTER' 카테고리의 다른 글

flutter - dart문법 final const 차이  (0) 2023.11.30
Flutter 상태관리(provider)  (1) 2022.12.06
Flutter - firebase 앱 연동  (0) 2022.03.21
Flutter - Getx  (0) 2022.03.16
Flutter - StatefulWidget Life cycle  (0) 2022.03.16
Comments