코딩하는 제리

[Flutter/Project](Instagram Clone) 포스트 생성시 작성할 데이터 파일 post model 본문

Flutter/Project_InstaClone(완)

[Flutter/Project](Instagram Clone) 포스트 생성시 작성할 데이터 파일 post model

JerryCho 2021. 2. 27. 11:09


소스코드 및 pubspec.yaml

// models/firestore/post_model.dart

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter_project_IJ/constants/firestore_keys.dart';

class PostModel {
  final String postKey;
  final String userKey;
  final String username;
  final String postImg;

  // 해당 유저의 userKey를 저장해놓고 likes를 취소할 때
  // userKey를 삭제한 후 list의 길이를 사용.
  final List<dynamic> numOfLikes;
  final String caption;
  final String lastCommentor;
  final String lastComment;
  final DateTime lastCommentTime;
  final int numOfComments;
  final DateTime postTime;
  final DocumentReference reference;

  // fromMap -> dart 내부 메서드
  PostModel.fromMap(Map<String, dynamic> map, this.postKey, {this.reference})
      : userKey = map[KEY_USERKEY],
        username = map[KEY_USERNAME],
        postImg = map[KEY_POSTIMG],
        numOfLikes = map[KEY_NUMOFLIKES],
        caption = map[KEY_CAPTION],
        lastCommentor = map[KEY_LASTCOMMENTOR],
        lastComment = map[KEY_LASTCOMMENT],

        // Firebase에서 전달되어 오면 String 타입이므로 Timestamp로 바꿔준다.
        // 만약 데이터가 비어있다면 Timestamp로 바꾸는데 에러가 발생할 것이기에 그 즉시 시간을 넣어줌.
        lastCommentTime = map[KEY_LASTCOMMENTTIME] == null
            ? DateTime.now().toUtc()
            : (map[KEY_LASTCOMMENTTIME] as Timestamp).toDate(),
        postTime = map[KEY_POSTTIME] == null
            ? DateTime.now().toUtc()
            : (map[KEY_POSTTIME] as Timestamp).toDate(),
        numOfComments = map[KEY_NUMOFCOMMENTS];

  // fromSnapshot -> cloud_firestore 메서드
  // snapshot -> FireStore 각각의 Document
  // id -> Document 키
  // reference -> 해당 Document 위치값
  // snapshot을 받아와서 PostModel로 변경.
  PostModel.fromSnapshot(DocumentSnapshot snapshot)
      : this.fromMap(snapshot.data(), snapshot.id,
            reference: snapshot.reference);

  // static은 인스턴스를 생성하지 않아도 호출이 가능함.
  // 포스트 데이터 생성.
  static Map<String, dynamic> getMapForeCreatePost(
      {String userKey, String username, String caption}) {
    Map<String, dynamic> map = Map();
    map[KEY_USERKEY] = userKey;
    map[KEY_USERNAME] = username;
    map[KEY_POSTIMG] = "";
    map[KEY_NUMOFLIKES] = [];
    map[KEY_CAPTION] = caption;
    map[KEY_LASTCOMMENTOR] = "";
    map[KEY_LASTCOMMENT] = "";
    map[KEY_LASTCOMMENTTIME] = DateTime.now().toUtc();
    map[KEY_POSTTIME] = 0;
    map[KEY_NUMOFCOMMENTS] = DateTime.now().toUtc();
    return map;
  }
}
Comments