Flutter

[Flutter] #3 Firebase 없이 구글 로그인 구현

yun.data 2025. 4. 2. 00:31

 

1. 패키지 설치 후 실행

//pubspec.yaml
dependencies:
  google_sign_in: ^6.1.4
  http: ^0.13.6

 

// terminal
flutter pub get

 

 

2. import

import 'package:google_sign_in/google_sign_in.dart'; 
import 'constants.dart' // base URL이 기록된 상수 정의 파일

 

백엔드 주소를 하드코딩 하지 않고 상수 정의 파일을 이용하여 일괄 관리함

 

 

3. 구글 로그인 처리 함수 구현

// welcome_screen.dart

Future<void> handleGoogleSignIn(BuildContext context) async {
  final GoogleSignIn _googleSignIn = GoogleSignIn(
    scopes: ['email', 'profile'],
  );

  try {
    final GoogleSignInAccount? googleUser = await _googleSignIn.signIn();

    if (googleUser == null) return; // 사용자가 로그인 취소한 경우

    final GoogleSignInAuthentication googleAuth = await googleUser.authentication;
    final idToken = googleAuth.idToken;

    if (idToken != null) {
      final response = await http.post(
        Uri.parse('$baseUrl/api/auth/google'),
        headers: {'Content-Type': 'application/json'},
        body: jsonEncode({'idToken': idToken}),
      );

      if (response.statusCode == 200) {
        Navigator.pushReplacement(
          context,
          MaterialPageRoute(builder: (_) => const MainScreen()),
        );
      } else {
        print('백엔드 로그인 실패: ${response.body}');
      }
    }
  } catch (e) {
    print('구글 로그인 실패: $e');
  }
}

 

 

 

4. 구글 로고 파일 다운로드 후 적용

https://developers.google.com/identity/branding-guidelines#matching

 

Sign in with Google Branding Guidelines  |  Google Identity  |  Google for Developers

Send feedback Sign in with Google Branding Guidelines Stay organized with collections Save and categorize content based on your preferences. This document provides guidelines on how to display a Sign in with Google button on your website or app. Your websi

developers.google.com

 

assets 폴더 생성 후 다운로드한 이미지 업로드 - pubspec.yaml 파일 수정

// pubspec.yaml
assets:
    - assets/google_logo.png

 

 

 

5. 버튼에 적용

                  customSocialButton(
                    assetPath: 'assets/google_logo.png',
                    text: 'Google 로그인',
                    backgroundColor: const Color(0xFFf2f2f2),
                    textColor: Colors.black,
                    onPressed: () => handleGoogleSignIn(context),
                  ),

 

구현한 커스텀 버튼은 아래와 같음

 

Widget customSocialButton({
    required String assetPath,
    required String text,
    required Color backgroundColor,
    required Color textColor,
    required VoidCallback onPressed,
  }) {
    return ElevatedButton(
      onPressed: onPressed,
      style: ElevatedButton.styleFrom(
        backgroundColor: backgroundColor,
        foregroundColor: textColor,
        minimumSize: const Size.fromHeight(48),
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
        elevation: 0,
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          Image.asset(assetPath, height: 24),
          const SizedBox(width: 16),
          Expanded(
            child: Text(
              text,
              textAlign: TextAlign.center,
              style: TextStyle(fontSize: 16, color: textColor),
            ),
          ),
          const SizedBox(width: 40),
        ],
      ),
    );
  }
}