월루를 꿈꾸는 대학생

[Flutter] Firebase 연동해서 회원가입 로그인 기능 추가 본문

Programing/플러터

[Flutter] Firebase 연동해서 회원가입 로그인 기능 추가

하즈시 2022. 12. 30. 00:40
728x90

https://pub.dev/packages/firebase_core/install

 

firebase_core | Flutter Package

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

pub.dev

 

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

 

 

// 해당 인스턴스는 사용자 등록과 인증에 사용
final _authentication = FirebaseAuth.instance;

 

해당 인스턴스를 통해서 로그인이 가능

이 인스턴스를 통해서 계정과 연동되어 있는 파이어베이스랑 어플이랑 데이터 주고받으면서 인증절차를 해줌

 

전송버튼 누를 때 실행 필요 

 

 

onTap: () async {
  // 회원가입 스크린인 경우
  if (isSignupScreen) {
    _tryValidation();
    try {
      // create ~ 메서드가 future값을 반환함
      final newUser = await _authentication
          .createUserWithEmailAndPassword(
        email: userEmail,
        password: userPassword,
      );
      //회원가입 성공시 화면 이동
      if (newUser.user != null) {
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) {
              return ChatScreen();
            },
          ),
        );
      }
    } catch (e) {
      print(e);
      ScaffoldMessenger.of(context).showSnackBar(SnackBar(
        content:
            Text('Please check your email and password'),
        backgroundColor: Colors.blue,
      ));
    }
  }

  // print(userName );
  // print(userPassword);
  // print(userEmail);
},

 

회원가입이 제대로 된 경우 textformfield에서 받은 값들로 유저가 생성됨을 확인

 

 

로그인 할 때 

- textformfield에 있는 값들 가지고 온 다음 _authentication에 있는 메서드로 유저가 맞는지 확인

if (!isSignupScreen) {
    //유효성 검사
    _tryValidation();
    try {
      // 유저가 입력한 이메일 비번 가져오기
      final newUser =
          await _authentication.signInWithEmailAndPassword(
        email: userEmail,
        password: userPassword,
      );
      // 로그인 성공시 화면 이동
      if (newUser.user != null) {
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) {
              return ChatScreen();
            },
          ),
        );
      }
    } catch (e) {print(e);}
  }
},

 

 

로그아웃용 

- signOut 메서드로 로그아웃기능 추가

appBar: AppBar(
  title: Text('Chat screen'),
  actions: [
    IconButton(
      // 로그아웃
      onPressed: () {
        _authentication.signOut();
        Navigator.pop(context);
      },
      icon: const Icon(
        Icons.exit_to_app,
        color: Colors.white,
      ),
    ),
  ],

 

728x90