hoony's web study

728x90
반응형

1. Facebook Developer Setting + Google Firebase Setting

 

https://developers.facebook.com/

 

Meta for Developers

메타버스에서 선보이는 창의성 경험하기 10월 11일에 열리는 Meta Connect에서 전 세계의 혁신가들을 만나보세요. 메타버스의 아름답고 긴밀히 연결된 세상을 함께 구상할 방법을 알아보세요. 저장

developers.facebook.com

 

 

본 게시글에서는 로그인 기능만 구현을 할 것이기 때문에, 소비자를 택한 후 앱 만들기를 진행해줍니다.

 

 

앱 ID와 앱 시크릿 코드를 미리 복사해두도록 합시다.

 

 

구글 파이어베이스에서 Authentication 에 Facebook 을 등록해주고,

아까 복사해두었던 앱ID와 앱시크릿코드를 기입해주도록 합니다.

이후, 아래 OAuth 리디렉션 URI를 복사해둔 후, 아래 스크린샷 대로 설정을 해주도록 합니다.

 

 

 

2. Project Setting

이전에 다루었던, Google Login 게시글의 방식대로 세팅하도록 하겠습니다.

https://islet4you.tistory.com/entry/Google-Login-Android-%EA%B5%AC%ED%98%84

 

[Flutter] Google Login - Android 구현

1. Google Cloud 에 프로젝트와 인증 절차 설정 https://console.cloud.google.com/ Google 클라우드 플랫폼 로그인 Google 클라우드 플랫폼으로 이동 accounts.google.com 프로젝트 생성 후, 해당 프로젝트를 선..

islet4you.tistory.com

[pubspec.yaml]

flutter_facebook_auth: ^4.4.1+1
firebase_core: ^1.22.0
firebase_auth: ^3.9.0

 

해당 의존성을 주입 후 flutter pub get 명령어 수행

 

[login_with_facebook.dart]

import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter_facebook_auth/flutter_facebook_auth.dart';

class FacebookSignInApi {
  static Future<UserCredential?> login() async {
    try {
      LoginResult result = await FacebookAuth.instance.login();

      OAuthCredential facebookAuthCredential =
      FacebookAuthProvider.credential(result.accessToken!.token);

      UserCredential? userCredential = await FirebaseAuth.instance.signInWithCredential(facebookAuthCredential);

      return userCredential;
    } catch (err) {
      print(err);
    }
  }

  static Future logout() async {
    await FacebookAuth.instance.logOut();
  }
}

 

[facebook_logged_in_page.dart]

 

class FacebookLoggedInPage extends StatelessWidget {
  final UserCredential userCredential;

  FacebookLoggedInPage({
    Key? key,
    required this.userCredential,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Logged In'),
        centerTitle: true,
      ),
      body: Container(
        alignment: Alignment.center,
        color: Colors.blueGrey.shade900,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            TextButton(
              child: const Text('Logout'),
              onPressed: () async {
                await FacebookSignInApi.logout();

                Navigator.of(context).pushReplacement(MaterialPageRoute(
                  builder: (context) => Login(),
                ));
              },
            ),
            const Text(
              'Profile',
              style: TextStyle(fontSize: 24),
            ),
            const SizedBox(height: 32),
            CircleAvatar(
                radius: 40,
                backgroundImage: NetworkImage(userCredential.user?.photoURL ??
                    'https://www.gravatar.com/avatar/00000000000000000000000000000000?d=mp&f=y')),
            const SizedBox(height: 8),
            Text(
              'Name: ${userCredential.user?.displayName}',
              style: const TextStyle(color: Colors.white, fontSize: 24),
            )
          ],
        ),
      ),
    );
  }
}

 

[login.dart]

 

class Login extends StatelessWidget {
  const Login({Key? key}) : super(key: key);

  Future<UserCredential?> loginWithFacebook(BuildContext context) async {
    UserCredential? userCredential = await FacebookSignInApi.login();

    if (userCredential != null) {
      print('로그인 성공 === Facebook');
      print(userCredential);

      Navigator.of(context).pushReplacement(MaterialPageRoute(
          builder: (context) => FacebookLoggedInPage(userCredential: userCredential)
      ));
    } else {
      ScaffoldMessenger.of(context)
          .showSnackBar(SnackBar(content: Text('로그인 실패 === Facebook')
      ));
    }

    return userCredential;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('SNS LOGIN'),
      ),
      body: Center(
        child: Column(
          children: [
            const SizedBox(
              height: 200,
            ),
            const SizedBox(height: 16),
            SizedBox(
              width: 180.0,
              height: 48.0,
              child: ElevatedButton.icon(
                style: ElevatedButton.styleFrom(
                  side: const BorderSide(
                    width: 5.0,
                    color: Colors.blueAccent,
                  ),
                  primary: Colors.blueAccent,
                  onPrimary: Colors.black,
                  minimumSize: const Size(double.infinity, 50),
                ),
                icon: const FaIcon(
                  FontAwesomeIcons.facebook,
                  color: Colors.white,
                ),
                label: Text('Facebook 로그인'),
                onPressed: () async {
                  await loginWithFacebook(context);
                },
              ),
            ),

          ],
        ),
      ),
    );
  }


}

 

위와 같이 코드를 작성 후 main.dart에서 login.dart 를 호출하시면 아래와 같이 잘 작동하는 것을 확인 할 수 있습니다.

 

728x90

공유하기

facebook twitter kakaoTalk kakaostory naver band
loading