본문 바로가기

플러터(Flutter)

Flutter Firestore 연동

1. flutter에 firestore 플러그인 추가

1-1. 플러그인 추가

firestore 관련 플러그인 추가

flutter pub add cloud_firestore
flutterfire configure

 

2-2. flutter 프로젝트 코드 수정 후 빌드

import 'package:cloud_firestore/cloud_firestore.dart';

 

1-2. 빌드 에러 핸들링

이때 빌드 시 에러 발생

에러 내용대로 android/app/build.gradle 파일에 minSdkVersion을 19로 수정 후 다시 빌드

    defaultConfig {
        // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
        applicationId "com.example.pineapple_tok"
        // You can update the following values to match your application needs.
        // For more information, see: https://docs.flutter.dev/deployment/android#reviewing-the-gradle-build-configuration.
        minSdkVersion 19
        targetSdkVersion flutter.targetSdkVersion
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
    }

 

이번에는 DexArchiveMergerException 관련 에러 발생

android/app/build.gradle 파일에 아래 2줄을 추가

DexArchiveMergerException 에러 해결 용 코드
-  multiDexEnabled true
-  implementation 'com.android.support:multidex:2.0.1'
    defaultConfig {
        // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
        applicationId "com.example.pineapple_tok"
        // You can update the following values to match your application needs.
        // For more information, see: https://docs.flutter.dev/deployment/android#reviewing-the-gradle-build-configuration.
        minSdkVersion 19
        targetSdkVersion flutter.targetSdkVersion
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
        multiDexEnabled true
    }
 ...
    dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'com.android.support:multidex:2.0.1'
}

 

이 후 정상적으로 빌드 되는 것을 확인

 

2. Firebase에 데이터베이스 추가하기

2-1. Firestore Database 생성하기

firebase 콘솔로 이동 후, 빌드 -> Firestore Database 클릭 -> 데이터베이스 만들기 클릭

이때 테스트 모드에서 시작 선택해야 제약없이 사용이 가능

다음 선택 후 지역은 기본값으로 선택 후 생성 클릭

 

2-2. 컬렉션 및 문서 생성

생성 후 컬렉션 시작을 클릭,

그 후 문서를 추가\

 

firestore는 컬렉션 -> 문서 -> 필드값 or 컬렉션 구조로 이루어져 있다.

즉 컬렉션 생성 후 문서 생성이 원칙.

빨간색 - 콜렉션

파란색 - 문서

노란색 - 문서의 필드 값

 

현재 예제로 생성된 데이터는 user(콜렉션) -> Pcb6GpXLiBuBQtXXG1Vc(문서, ID 자동 생성) -> profile(콜렉션) ->
Cvfkl6Qk1PceIZpILdtzX3rMhcT2(문서, uid로 생성) -> 데이터 로 이루어져 있다.

 

문서 개수가 현재 user profile의 개수

 

3. firestore에서 데이터 가져오기

firestore instance를 생성한 후, 아래 코드처럼 for문을 이용해 모든 문서에 접근이 가능하다.

  Future<List<Friend>?> updateFriendList() async {
    final collectionRef = _firestore.collection('user').doc('Pcb6GpXLiBuBQtXXG1Vc').collection('profile');
    final querySnapshot = await collectionRef.get();

    List<String> friendIdList = await getFriendsList();

    List<Friend> friendList = [];
    for (var doc in querySnapshot.docs) {
      if (friendIdList.contains(doc.id)) {
        String thumbnail = doc['thumbnail'];
        String background = doc['background'];
        String name = doc['name'];
        String comment = doc['comment'];
        friendList.add(Friend.getFriendProfile(thumbnail, background, name, comment));
      }
    }

    if (friendList.length == 0) {
      return null;
    }
    else {
      return friendList;
    }
  }

 

또는 문서ID를 직접 지정해서 데이터를 가져올 수도 있다.

class MyProfileHandler {
  final _authentication = FirebaseAuth.instance;
  final _firestore = FirebaseFirestore.instance;

  Future<MyProfile?> updateMyProfile() async {
    final curUser = _authentication.currentUser;

    final docRef = _firestore.collection('user').doc('Pcb6GpXLiBuBQtXXG1Vc')
      .collection('profile').doc(curUser!.uid);
    final doc = await docRef.get();

    if (doc.exists) {
      String thumbnail = doc['thumbnail'];
      String background = doc['background'];
      String name = doc['name'];
      String comment = doc['comment'];
      return MyProfile.getMyProfile(thumbnail, background, name, comment);
    }
    else {
      return null;
    }
  }
}

 

참고 사이트:

https://firebase.google.com/docs/firestore/query-data/get-data?hl=ko 

https://jh-industry.tistory.com/56