【간단】Flutter 앱의 Firebase 연결 방법!!

이번에는, Flutter 앱에서 FireBase를 사용할 수 있도록 절차를 소개하겠습니다. 기본적으로 공식의 다음 절차를 바탕으로 진행하고 있습니다.

<공식>Flutter 앱에 Firebase 추가

하지만 저의 경우, 막힌 부분도 많았기 때문에 그 대처 방법도 포함하여 소개하겠습니다.

환경

저의 환경은 다음과 같습니다.

  • Windows11
  • VSCode
  • Flutter 3.22.3
  • Google Pixel [Android](디버깅용 스마트폰)

준비물

이 절차를 수행하려면 다음이 필요합니다.

이 시점에서 새롭게 FireBase 프로젝트를 준비할 필요는 없습니다. 이미 프로젝트를 생성한 경우, 그것을 사용할 수도 있습니다.

Firebase CLI 설치

Firebase CLI는 Firebase에 연결하기 위한 CLI(Command Line Interface)입니다. FireBase에 액세스하려면 Firebase CLI가 필요합니다. 다음 공식 절차를 참고하여 설치하십시오.
<공식>Firebase CLI 참고

저는 VSCode의 터미널에서 실행하고 싶었기 때문에, npm으로 설치를 진행했습니다. 참고로 npm으로 설치 절차를 소개합니다.

Node.js 설치

이미 설치되어 있으면 생략하십시오. 다음에서 Node.js 설치 프로그램을 다운로드하고 Node.js를 설치하십시오.
https://nodejs.org/en

Firebase CLI 설치

다음 명령어를 터미널에서 실행하십시오.

npm install -g firebase-tools

이제 Firebase CLI의 준비는 완료되었습니다.

FireBase에 로그인

터미널에서 다음 명령어를 실행하고 FireBase에 로그인합니다.

firebase login

다음과 같이 Google의 계정 화면이 열리면 관리할 계정을 선택하십시오.

FlutterFire CLI 설치

FlutterFire CLI는 Flutter 앱을 Firebase에 연결하기 위한 Flutter 플러그인의 세트입니다. 터미널에서 다음 명령어를 실행하고 FireBase에 로그인합니다.

dart pub global activate flutterfire_cli

Flutter 앱의 Firebase 연결 설정

터미널에서 다음 명령어를 실행하고 FireBase 연결 설정을 수행합니다.

flutterfire configure

오류: flutterfire: command not found

위 명령어를 실행하면 “flutterfire: command not found”라는 오류가 발생할 수 있습니다.

시스템 환경 변수를 설정하여 이 오류를 해결할 수 있습니다.

시스템 환경 변수의 Path에 다음을 추가하십시오.

C:\Users\{UserName}\AppData\Local\Pub\Cache\bin

오류: FirebaseCommandException

위 방법을 적용하면 새롭게 “FirebaseCommandException: An error occurred on the Firebase CLI when attempting to run COMMAND: firebase projects:list –json”이라는 오류가 발생할 수 있습니다.

이것은 로그인이 제대로 되지 않았기 때문에 발생합니다. 터미널에서 다음 명령어를 실행하고 다시 로그인하십시오.

firebase login --reauth

프로젝트 선택

“flutterfire configure”를 실행하면 다음과 같이 어떤 프로젝트를 선택할지 묻습니다. 기존 프로젝트를 선택하거나 “create a new project”를 선택하여 새 프로젝트를 생성합니다.

프로젝트 선택 후, 플랫폼을 선택하면 FireBase에 연결하기 위한 설정이 Flutter 앱 프로젝트에 반영됩니다.

firebase_core 설치

pubspec.yaml에 firebase_core를 추가합니다. (버전은 임의로 설정)

dependencies:
  firebase_core: ^3.2.0

main.dart 설정

main.dart에 FireBase와 연결하기 위한 초기 처리를 작성합니다.

Future<void> main() async {
  // firebase
  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );

실행 중 오류 발생…

저의 경우, 위 설정 후 디버그 모드로 실행해본 결과 다음과 같은 오류가 발생했습니다. “com.google.gms:google-services”의 클래스패스를 찾을 수 없다는 오류입니다.

Could not find method classpath() for arguments [com.google.gms:google-services:4.3.15]
 on root project 'android' of type org.gradle.api.Project.

대처 방법

다음 세 파일을 수정합니다.

  • android\build.gradle
  • android\settings.gradle
  • android\app\build.gradle

android\build.gradle

“buildscript” 부분을 삭제합니다.

- buildscript {
-     ext.kotlin_version = '1.7.10'
-     repositories {
-         google()
-         mavenCentral()
-     }
-     dependencies {
-         // START: FlutterFire Configuration
-         classpath 'com.google.gms:google-services:4.3.15'
-         // END: FlutterFire Configuration
-         classpath 'com.android.tools.build:gradle:7.3.0'
-         classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
-     }
- }

 allprojects {
     repositories {
         google()
         mavenCentral()
     }
 }

android\settings.gradle

“plugins”에 다음과 같이 “com.google.gms.google-services”를 추가합니다. (버전은 임의로 설정)

 plugins {
     id "dev.flutter.flutter-plugin-loader" version '1.0.0'
     id "com.android.application" version '7.3.0' apply false
     id "org.jetbrains.kotlin.android" version '1.7.10' apply false
+    id "com.google.gms.google-services" version '4.3.15' apply false
 }

android\app\build.gradle

다음과 같이 “flutterfire configure” 명령 실행 시 자동으로 추가된 “apply plugin: ‘com.google.gms.google-services'”를 삭제하고, 다음과 같이 “id “com.google.gms.google-services””를 추가합니다.

 plugins {
     id "com.android.application"
-    // START: FlutterFire Configuration\
-    apply plugin: 'com.google.gms.google-services'
+    id "com.google.gms.google-services"
-    // END: FlutterFire Configuration
     id "org.jetbrains.kotlin.android"
     id "dev.flutter.flutter-gradle-plugin"
 }

아직도 오류 발생…

다시 디버그 실행하면 이번에는 다음과 같은 메시지가 표시됩니다. minSdkVersion 버전이 맞지 않다는 메시지입니다.

│ android {                                                                                     │
│   defaultConfig {                                                                             │
│     minSdkVersion 23                                                                          │
│   }                                                                                           │
│ }                                                                                             │
│                                                                                               │
│ Following this change, your app will not be available to users running Android SDKs below 23. │
│ Consider searching for a version of this plugin that supports these lower versions of the     │
│ Android SDK instead.                                                                          │
│ For more information, see:                                                                    │
│ https://docs.flutter.dev/deployment/android#reviewing-the-gradle-build-configuration          │
└───────────────────────────────────────────────────────────────────────────────────────────────┘
Error: Gradle task assembleDebug failed with exit code 1

대처 방법 1

android\build.gradle에 다음과 같은 내용이 있기 때문에 다음과 같이 수정합니다.

 defaultConfig {
-        minSdkVersion flutter.minSdkVersion
+        minSdkVersion 23
 }

대처 방법 2

혹은, Flutter JDK의 다음 파일에 기재된 minSdkVersion의 기본값을 변경합니다. “…\flutter\packages\flutter_tools\gradle\src\main\groovy\flutter.groovy”

 class FlutterExtension {
     /** Sets the compileSdkVersion used by default in Flutter app projects. */
     public final int compileSdkVersion = 34
     /** Sets the minSdkVersion used by default in Flutter app projects. */
-    public  final int minSdkVersion = 19
+    public  final int minSdkVersion = 23
}

앞으로 만들 앱도 FireBase에 접근할 가능성이 있기 때문에, 저는 이 방법으로 대처했습니다.

디버그가 가능한 것을 확인!

다시 디버그 실행을 해보니, 무사히 실행되었습니다!

Launching lib\main.dart on Pixel X in debug mode...
Picked up JAVA_TOOL_OPTIONS: -Dfile.encoding=UTF-8 -Dsun.jnu.encoding=UTF-8

√ Built build\app\outputs\flutter-apk\app-debug.apk
Connecting to VM Service at ws://127.0.0.x:xxxx/vv-oYScA6OI=/ws
제목과 URL을 복사했습니다