앱 개발/Flutter
55. [Flutter] Flutter에서 Firestore 쿼리 사용법
mroh1226
2024. 1. 23. 18:09
반응형
Firestore의 CRUD를 Repository에서 어떻게 이용하는지 알아봅니다.
Model
Movie
class Movie {
String movieCode;
String movieName;
int score;
Movie({
required this.movieCode,
required this.movieName,
required this.score,
});
//Json 데이터 -> Movie로 변환
Movie.fromJson({required Map<String, dynamic> json})
: movieCode = json["movieCode"],
movieName = json["movieName"],
score = json["score"];
//Movie -> Json 데이터로 변환
Map<String, dynamic> toJson() {
return {
"movieCode": movieCode,
"movieName": movieName,
"score": score,
};
}
}
Repository
instance 생성 (FirebaseFirestore 사용을 위함)
final FirebaseFirestore _firestore = FirebaseFirestore.instance;
데이터 추가 생성 (Create)
데이터 추가 생성 시, Document 이름을 자동으로 생성할 경우 (랜덤한 문자열로 생성됨)
//삽입(document명 자동 생성)
Future<void> insertMovie(Movie movie) async {
final movieToJson = movie.toJson();
await _firestore.collection("movies").add(movieToJson);
}
데이터 추가 생성 시, Document 이름을 지정하여 생성할 경우
//삽입(document명 지정 생성)
Future<void> insertMovieCustom(Movie movie) async {
final movieToJson = movie.toJson();
await _firestore.collection("movies").doc("firstMovie").set(movieToJson);
}
데이터 조회(Read)
특정 값을 갖는 Document 데이터 가져오기
//조회
Future<Map<String, dynamic>?> getMovie(String movieCode) async {
final movie = await _firestore.collection("movies").doc(movieCode).get();
return movie.data();
}
특정 Collection에 포함되어있는 모든 Document 가져오기
//전체 조회
Future<List<Movie>> getAllmovie() async {
final querySnapshot = await _firestore.collection("movie").get();
return querySnapshot.docs
.map((movie) => Movie.fromJson(json: movie.data()))
.toList();
}
실시간 조회하기
//조회(실시간 Real Time)
Future<Map<String, dynamic>?> getMovieStream(String movieCode) async {
final movie = _firestore.collection("movies").doc(movieCode).snapshots();
await for (DocumentSnapshot snapshot in movie) {
Map<String, dynamic>? data = snapshot.data() as Map<String, dynamic>?;
return data ?? {};
}
return null;
}
조건을 걸어 조회하기
//특정 조건 조회 및 정렬하기
Future<QuerySnapshot<Map<String, dynamic>>> getMoviePopular() async {
final movie = _firestore
.collection("movies")
.where("score", isGreaterThan: 10000000) //1000만이 넘을 것
.where("movieCode", isNull: false) //movieCode가 null이 아닌 것
.where("movieName", isNull: false) //movidName이 null이 아닌 것
.orderBy("movieCode",descending: true) //내림차순으로 정렬
.get();
return movie;
}
- Firestore 조건문 종류: https://cloud.google.com/firestore/docs/query-data/queries?hl=ko#dart_3
데이터 쿼리 및 필터링 | Firestore | Google Cloud
데이터 쿼리 및 필터링 Firestore는 컬렉션 또는 컬렉션 그룹에서 검색할 문서를 지정할 수 있는 강력한 쿼리 기능을 제공합니다. 데이터 가져오기 및 실시간 업데이트 가져오기의 설명대로 이러
cloud.google.com
데이터 수정(Update)
기존 Document에서 Json 데이터 통으로 수정하기
//업데이트
Future<void> updateMovie(Movie movie) async {
final movieToJson = movie.toJson();
await _firestore.collection("movies").doc(movie.movieCode).update(movieToJson);
}
지정된 Document의 특정 Field 값만 수정하기
//해당 movieCode의 score 수정하기
Future<void> updateMovieScore(Movie movie, int score) async {
await _firestore
.collection("movies")
.doc(movie.movieCode)
.update({"score": score});
}
값의 유무에 따라 삽입 또는 수정하기
//삽입 또는 업데이트
Future<void> setMovie(Movie movie) async {
final movieToJson = movie.toJson();
await _firestore.collection("movies").doc(movie.movieCode).set(movieToJson);
}
데이터 삭제(Delete)
Document 삭제하기
//삭제
Future<void> deleteMovie(String movieCode) async {
await _firestore.collection("movies").doc(movieCode).delete();
}
}
Field 삭제하기
//특정 Field 삭제하기
Future<void> deleteMovieField(String movieCode) async {
await _firestore.doc(movieCode).update({"movieName": FieldValue.delete()});
}
트랜젝션(Transaction) 태우기
Transaction 으로 데이터 처리하기
//트렌젝션으로 데이터 처리하기
Future<void> tranUpdateMovie() async {
final firstMovie = _firestore.collection("movies").doc("firstMovie");
_firestore.runTransaction((transaction) async {
final snapshot = await transaction.get(firstMovie);
final score = snapshot.get("score") + 1;
transaction.update(firstMovie, {"score": score});
}).then((value) => print("성공적으로 업데이트 되었습니다."),
onError: (e) => print("에러발생"));
}
일괄 쓰기 작업 만들기(Batch)
batch 로 set(), update(), delete() 조합하여 한번에 처리하기
//batch로 set, update, delete 작업 조합 사용하기
Future<void> batchMovie() async {
final batch = _firestore.batch();
//movies 컬랙션의 favoritMovie 다큐먼트
final docMovie = _firestore.collection("movies").doc("favoriteMovie");
batch.set(docMovie, {"movieCode": "168863"}); // movieCode 필드에 "168863" set()함
batch.set(docMovie, {"movieName": "GET OUT"}); // movieName 필드에 "GET OUT" set()함
batch.update(docMovie, {"score": "2130000"}); // score 필드에 2130000으로 update()
batch.delete(docMovie); //삭제
//batch를 커밋하여 한번에 처리함
batch.commit();
}
- 참고 사이트: https://firebase.google.com/docs/firestore/manage-data/transactions?hl=ko
트랜잭션 및 일괄 쓰기 | Firestore | Firebase
Firebase 데모 데이가 시작되었습니다. Google 최고의 기술을 활용하여 AI 기반 풀 스택 앱을 빌드하고 성장시키는 방법에 관한 데모를 시청하세요. 의견 보내기 트랜잭션 및 일괄 쓰기 컬렉션을 사
firebase.google.com
- firestore에 대해 잘 정리된 Funncy님의 블로그글: https://funncy.github.io/flutter/2021/03/06/firestore/
[Flutter] - Firebase FireStore 총정리
Flutter에서 FireStore 사용했던 내용을 기록하였다.
funncy.github.io
반응형