>

상세 컨텐츠

본문 제목

[부트캠프] 7주차 1

0. 창업

by 마켓플레이어, 마케터 봉 2025. 4. 15. 14:35

본문

파이어베이스 복습 및 정리

 

#### 기본 세팅
1. Firebase에서 프로젝트 생성
- 1개의 계정에 프로젝트별 속성 추가 가능.
- 앱 전용 계정을 만들어, 하위 속성으로 앱들 배치.

2. Firebase CLI 설치 : 터미널 메인 내
```
curl -sL https://firebase.tools | bash
```

3. Firebase 로그인
```
firebase login
```

4. FlutterFire CLI 설치 : Firebase 2단계
```
dart pub global activate flutterfire_cli
```

5. Firebase와 연결할 Flutter 앱의 경로로 이동, 아래 명령어 입력
```
flutterfire configure
```

6. 사용할 플랫폼(iOS, android, web 등) 선택
![이렇게 뜸](https://img1.daumcdn.net/thumb/R1280x0/?scode=mtistory2&fname=https%3A%2F%2Fblog.kakaocdn.net%2Fdna%2F6q817%2FbtrQ0vJNY2P%2FAAAAAAAAAAAAAAAAAAAAAKMJZ2z8aXo1kYvNFDNj6nqO8hSiOf7X3tVSgKvFI_hP%2Fimg.png%3Fcredential%3DyqXZFxpELC7KVnFOS48ylbz2pIh7yKj8%26expires%3D1753973999%26allow_ip%3D%26allow_referer%3D%26signature%3DYiJxPljBDkvoAv%252BystWFsyFed18%253D)

7. 아래 명령어 실행
```
flutter pub add firebase_core
```

8. Firebase 초기화 : main()함수를 아래 코드로 대체
```dart hl:2 point2:3
void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
  runApp(const MyApp());
}
```
- 라인2 : Flutter 프레임워크가 완전히 초기화되었음을 보장하는 역할. await Firebase.initializeApp(); 같은 비동기 코드가 실행되기 전 Flutter가 완전히 초기화 되지 않을 수 있기에 이를 방지하기 위한 역할.
- 라인3 : 앱이 시작되기 전 Firebase 서비스를 초기화하는 역할.

9. iOS, android 최소지원 버젼 변경하기
- ios/Podfile에서 iOS 지원버젼 바꾸기(아래 이미지 참고)
![ios 버젼 변경](https://teamsparta.notion.site/image/https%3A%2F%2Fprod-files-secure.s3.us-west-2.amazonaws.com%2F83c75a39-3aba-4ba4-a792-7aefe4b07895%2F5cf8e18e-4c06-4aa8-a1c6-8e4a14d72ec0%2Fimage.png?table=block&id=1372dc3e-f514-81bb-b0c2-c11d6d5c9318&spaceId=83c75a39-3aba-4ba4-a792-7aefe4b07895&width=1310&userId=&cache=v2)

- android/app/build.gradle.kts에서 android 버젼 바꾸기
```kotlin
android {
    ndkVersion = "27.0.12077973"
    // 기존 설정들...
}
```

#### Fiebase 데이터 관리(CRUD) - Firestore 사용방법
- NoSQL 기반의 데이터베이스
- 구조
- 컬렉션(Collection) : 여러 문서를 그룹으로 묶는 개념
- 문서(Document) : 데이터의 기본 단위. key-value 형태로 값을 저장.
- 형식에 제한을 두지 않는 NoSQL이기 때문에 문서 안에 문서 형태로 저장 가능.
- 참고 : 파일을 저장할 수 있지만 용량 제한이 1MB 정도로 매우 낮아 활용도가 제한됨.
- 사용방법
- Firestore 객체 가지고 오기 → 컬렉션 참조 만들기 → 전체 문서 가져오기
- Firestore 객체 가지고 오기 → 컬렉션 참조 만들기 → 문서 참조 만들기 → CRUD(생성, 읽기, 수정, 삭제)

###### 패키지 추가하기
```
flutter pub add cloud_firestore
```

###### 컬렉션 내 문서 전체 조회
```dart hl:12,15,18-20
  Future<void> getAll() async {
    // 1. FirebaseFirestore 객체 가지고오기
    FirebaseFirestore firestore = FirebaseFirestore.instance;
    
    // 2. FirebaseFirestore 객체에서 collection 메서드를 통해 posts 컬렉션에 대한 참조 가지고 오기
    //    여기까지는 아무런 통신이 이루어 지지 않고 단순히 posts 컬렉션에 대한 참조만 저장!!(posts 컬렉션을 가지고 올거야 하고만 알려주는 단계)
    CollectionReference collectionRef = firestore.collection('posts');
    
    // 3. 컬렉션 참조에서 모든 문서(Document) 가지고오기
    //    이 때 Firestore에서 데이터 가지고옴
    //    결과가 QuerySnapshot 타입으로 전달됨
    QuerySnapshot snapshot = await collectionRef.get();
    
    // 4. QuerySnapshot객체 내에 docs 필드에 조회된 문서들의 결과가 들어있는데 QueryDocumentSnapshot 라는 타입임. 즉 문서 조회 결과
    List<QueryDocumentSnapshot> documentSnaphots = snapshot.docs;
    
    // 5. QueryDocumentSnapshot에서 data 메서드를 통해 진짜 데이터 가지고올 수 있음
    for (var docSnapshot in documentSnaphots) {
      print(docSnapshot.data());
    }
  }
```

###### 컬렉션 내 문서(데이터) 관리 - 생성(C)
```dart hl:14-19,22
  Future<void> insert() async {
    // 1. FirebaseFirestore 객체 가지고오기
    FirebaseFirestore firestore = FirebaseFirestore.instance;
    
    // 2. FirebaseFirestore 객체에서 collection 메서드를 통해 posts 컬렉션에 대한 참조 가지고 오기
    //    여기까지는 아무런 통신이 이루어 지지 않고 단순히 posts 컬렉션에 대한 참조만 저장!!
    CollectionReference collectionRef = firestore.collection('posts');
    
    // 3. 컬렉션 참조에서 문서(Document) 참조 만들기
    //    ID를 파라미터로 넣지 않으면 문서 생성 시 새로운 ID 부여!
    DocumentReference documentRef = collectionRef.doc();
    
    // 4. 문서에 넣을 데이터를 Map 타입으로 생성
    Map<String, dynamic> data = {
      'writer': '이지원',
      'title': '블로그 타이틀',
      'content': '내용입니다',
      'createdAt': DateTime.now().toIso8601String(),
    };
    
    // 5. 문서 참조의 set 메서드 안에 생성할 데이터 전달해주면 이때 생성!!!
    await documentRef.set(data);
  }
```

###### 컬렉션 내 문서(데이터) 관리 - 읽기/조회(R)
```dart hl:16
  Future<void> getOneById() async {
    // 1. FirebaseFirestore 객체 가지고오기
    FirebaseFirestore firestore = FirebaseFirestore.instance;
    
    // 2. FirebaseFirestore 객체에서 collection 메서드를 통해 posts 컬렉션에 대한 참조 가지고 오기
    //    여기까지는 아무런 통신이 이루어 지지 않고 단순히 posts 컬렉션에 대한 참조만 저장!!
    CollectionReference collectionRef = firestore.collection('posts');
    
    // 3. 컬렉션 참조에서 문서 ID에 대한 문서(Document) 참조 만들기
    //    파라미터로 아까 만들때 생성된 ID 값 넣으면 됨
    //    ID는 중복되면 안됨!!!!!
    DocumentReference documentRef = collectionRef.doc('문서 ID');
    
    // 4. 문서 참조의 정보를 기반으로 파이어스토어에서 문서 가지고옴!!!
    //    DocumentSnapshot 타입. 문서 조회결과
    DocumentSnapshot documentSnaphot = await documentRef.get();
    
    // 5. DocumentSnapshot의 data 메서드를 통해 진짜 데이터 가지고올 수 있음
    print(documentSnaphot.data());
  }
```
\
###### 컬렉션 내 문서(데이터) 관리 - 수정(U)
```dart hl:13-15,18
  Future<void> udpate() async {
    // 1. FirebaseFirestore 객체 가지고오기
    FirebaseFirestore firestore = FirebaseFirestore.instance;
    
    // 2. FirebaseFirestore 객체에서 collection 메서드를 통해 posts 컬렉션에 대한 참조 가지고 오기
    //    여기까지는 아무런 통신이 이루어 지지 않고 단순히 posts 컬렉션에 대한 참조만 저장!!
    CollectionReference collectionRef = firestore.collection('posts');
    
    // 3. 컬렉션 참조에서 문서(Document) 참조 만들기
    DocumentReference documentRef = collectionRef.doc('수정할 문서의 ID');
    
    // 4. 수정할 데이터를 Map 타입으로 생성
    Map<String, dynamic> data = {
      'writer': '오상구',
    };
    
    // 5. 문서 참조의 set 메서드 안에 생성할 데이터 전달해주면 이때 수정!!!
    await documentRef.set(data);
  }
```

###### 컬렉션 내 문서(데이터) 관리 - 삭제(D)
```dart hl:13
  Future<void> delete() async {
    // 1. FirebaseFirestore 객체 가지고오기
    FirebaseFirestore firestore = FirebaseFirestore.instance;
    
    // 2. FirebaseFirestore 객체에서 collection 메서드를 통해 posts 컬렉션에 대한 참조 가지고 오기
    //    여기까지는 아무런 통신이 이루어 지지 않고 단순히 posts 컬렉션에 대한 참조만 저장!!
    CollectionReference collectionRef = firestore.collection('posts');
    
    // 3. 컬렉션 참조에서 문서(Document) 참조 만들기
    DocumentReference documentRef = collectionRef.doc('삭제할 문서의 ID');
    
    // 4. 참조하고 있는 문서 삭제!!!
    await documentRef.delete();
  }
```


#### Fiebase 파일 관리(사진, 동영상 등 파일) - Storage 사용방법

###### 패키지 추가하기
```
flutter pub add firebase_storage
```

1. image_picker 를 통해 올릴 사진을 선택한다.
- 참고 : [[⭐️ Flutter 앱개발_참고 - 패키지#이미지 선택하기 - image_picker]]

2. 아래 예시코드를 응용해 Firebase Storage에 업로드 하고, 다운로드 링크를 얻는다.(필요시 서버 저장 or 사용자에게 보여주기)
```dart
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_storage/firebase_storage.dart';

class UploadImagePage extends StatefulWidget {
  @override
  _UploadImagePageState createState() => _UploadImagePageState();
}

class _UploadImagePageState extends State<UploadImagePage> {
  File? _image;
  String? _downloadURL;

  @override
  void initState() {
    super.initState();
    Firebase.initializeApp(); // 앱 실행 시 Firebase 초기화
  }

  // 이미지 선택
  Future<void> _pickImage() async {
    final pickedFile = await ImagePicker().pickImage(source: ImageSource.gallery);
    if (pickedFile != null) {
      setState(() {
        _image = File(pickedFile.path);
      });
    }
  }

  // Firebase에 이미지 업로드
  Future<void> _uploadImage() async {
    if (_image == null) return;

    final fileName = DateTime.now().millisecondsSinceEpoch.toString();
    final storageRef = FirebaseStorage.instance.ref().child('images/$fileName.jpg');

    try {
      await storageRef.putFile(_image!); // 이미지 업로드
      String downloadURL = await storageRef.getDownloadURL(); // 다운로드 URL 얻기

      setState(() {
        _downloadURL = downloadURL;
      });

      print("업로드 성공! 다운로드 링크: $downloadURL");
    } catch (e) {
      print("업로드 실패: $e");
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("Firebase Storage 예제")),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            _image != null ? Image.file(_image!, width: 200) : Text("이미지를 선택해주세요"),
            SizedBox(height: 20),
            ElevatedButton(onPressed: _pickImage, child: Text("이미지 선택")),
            ElevatedButton(onPressed: _uploadImage, child: Text("Firebase에 업로드")),
            if (_downloadURL != null)
              Text("다운로드 URL:\n$_downloadURL", textAlign: TextAlign.center),
          ],
        ),
      ),
    );
  }
}
```

반응형

관련글 더보기