>
파이어베이스 복습 및 정리
#### 기본 세팅
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 등) 선택

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 지원버젼 바꾸기(아래 이미지 참고)

- 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),
],
),
),
);
}
}
```
[부트캠프] 7주차 3 (0) | 2025.04.16 |
---|---|
[부트캠프] 7주차 2 (0) | 2025.04.15 |
[부트캠프] 6주차 5 - api 사용, 파이어베이스 사용 (0) | 2025.04.11 |
[부트캠프] 6주차 4 - 웹뷰 패키지 사용 방법 (0) | 2025.04.10 |
[부트캠프] 4주차 5 - 스플래시, 아이콘 패키지 사용 (0) | 2025.03.28 |