[Project] 2차 프로젝트 - 공용 클래스 만들기

김호정's avatar
Oct 25, 2024
[Project] 2차 프로젝트 - 공용 클래스 만들기
Book 테이블에만 존재하는 정보를 써야하는 경우에는
공용 Book 클래스를 만들어서 사용할 수 있다.
 
먼저 각 페이지 혹은 탭 화면별로 필요한 클래스는 vm에 언더바 ( _ ) 를 붙여서
전용 클래스로 만들어서 사용하다가 여기저기서 공통적으로 사용된다 싶으면 공용 클래스를 만들어서 사용하면 좋다.
 
 

공용 클래스 만들기

 
library 페이지에서 사용하는 Book 클래스
Book 테이블에
 
library_book.dart에 선언해놨다.
class Book { String isbn13; String title; String cover; String? author; String? pubDate; String? publisher; String? description; String? categoryId; int? sequence; bool? lendStatus; bool? reservationStatus; int? lendCount; int? reservationCount; int? likeCount; Book( {required this.isbn13, required this.title, required this.cover, this.author, this.publisher, this.categoryId, this.pubDate, this.description, this.sequence, this.lendStatus, this.reservationStatus, this.lendCount, this.reservationCount, this.likeCount}); Book.fromMap(map) : this.isbn13 = map['isbn13'], this.title = map['title'], this.author = map['author'], this.publisher = map['publisher'], this.categoryId = map['categoryId'], this.pubDate = map['pubDate'], this.cover = map['cover'], this.description = map['description'], this.sequence = map['sequence'], this.lendStatus = map['lendStatus'], this.reservationStatus = map['reservationStatus'], this.lendCount = map['lendCount'], this.reservationCount = map['reservationCount'], this.likeCount = map['likeCount']; }
 
 
 
필드를 모두 ? 처리해서 null 허용을 하고
생성자에는 named parameters(선택적 매개변수) 를 사용해서 필요한 경우만 넣어줄 수 있고 필요 없다면 안 넣어주면 된다.
 
이때 공용으로 사용할 때 무조건 필요한 것은 requried를 붙여주면 된다.
 
그리고 fromMap이라는 이름의 생성자를 만들어서 여기에 map을 넣어주면
Book클래스의 필드 이름과 같은 key값을 가지고 있는 map 정보를 가지고 Book 객체로 만들어 줄 수 있다.
 
파라미터 이름이 map인데 타입이 생략된 것이다.
 
주의
null 이 올 수 있는 값을 사용하는 곳에서 이 값으로 무언가 메서드를 호출한다던가 한다면 null 처리를 해줘야 한다. (아래 Lend 예시에서)
 
이런 처리를 하고 싶지 않으면 vm별로 언더바 ( _ )를 붙여서 전용 클래스를 만들고 해당 화면에 필요한 것들을 모두 required 처리해서 사용해도 무방하다.
 
 
 
 
Share article

keepgoing