https://github.com/kiwikid1543-alt/flutter_firebase_blog_app
블로그앱 ui 구성 후
class Post {
String id;
String title;
String content;
String writer;
String imageUrl;
DateTime createdAt;
Post({
required this.id,
required this.title,
required this.content,
required this.writer,
required this.imageUrl,
required this.createdAt,
});
// 1. fromJson 네임드 생성자 만들기
Post.fromJson(Map<String, dynamic> map)
: this(
id: map['id'],
title: map['title'],
content: map['content'],
writer: map['writer'],
imageUrl: map['imageUrl'],
createdAt: DateTime.parse(map['createdAt']),
);
// 2. toJson 메서드 만들기
Map<String, dynamic> toJson() {
return {
'id': id,
'title': title,
'content': content,
'writer': writer,
'imageUrl': imageUrl,
'createdAt': createdAt.toIso8601String(),
};
}
}
변수의 핵심 요소
변수의 동작 원리
변수를 선언하고 값을 할당하는 과정은 컴퓨터 메모리에서 다음과 같이 일어납니다.
선언: 컴퓨터에게 "데이터를 담을 공간을 확보해줘"라고 요청합니다.
할당: 확보된 공간(메모리 주소)에 실제 데이터를 넣습니다
참조: 변수 이름을 불러서 그 안에 들어있는 데이터를 가져옵니다.
생성자의 핵심 역할
객체의 탄생 (인스턴스화)
Post myPost = Post(...);라고 호출하는 순간, 생성자는 메모리의 빈 공간을 찾아 Post라는 상자를 만들고 그 안에 데이터를 채울 준비를 합니다.
데이터 초기화 (값 채우기)
설계도(class)에 선언된 변수들은 처음엔 비어 있거나 정의되지 않은 상태입니다. 생성자는 외부에서 받은 값('1', '반가워요' 등)을 클래스 내부의 변수(id, title 등)에 매칭해서 넣어주는 역할을 합니다.
초기화(Initialization)'라는 말은 어렵게 들릴 수 있지만, 사실 "변수에 처음으로 의미 있는 값을 집어넣어 사용할 준비를 마치는 것"을 의미합니다.