기초-중급
클래스
위젯, 모델, 서비스 객체를 이해하기 위한 클래스 구조를 익힙니다.
핵심 개념
클래스에서 읽어야 할 구성 요소
필드
객체가 가지고 있는 값입니다. Dart에서는 불변 모델을 만들기 위해 final 필드를 많이 사용합니다.
언제 쓰나: 객체가 기억해야 하는 속성을 표현할 때 사용합니다.
Flutter에서: StatelessWidget이 생성자로 받은 값을 final 필드에 저장합니다.
class Lesson {
// 강의 제목을 저장하는 필드입니다.
final String title;
// 완료 여부를 저장하는 필드입니다.
final bool done;
const Lesson({required this.title, this.done = false});
}
Container(
padding: const EdgeInsets.all(20),
decoration: BoxDecoration(
color: Colors.white,
border: Border.all(color: const Color(0xFFDCE6EF)),
borderRadius: BorderRadius.circular(8),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
decoration: BoxDecoration(
color: const Color(0xFFEEF7FB),
borderRadius: BorderRadius.circular(8),
),
child: const Text(
'클래스 활용 결과',
style: TextStyle(fontSize: 20, fontWeight: FontWeight.w900),
),
),
Wrap(
spacing: 8,
runSpacing: 8,
children: [
Chip(label: Text('클래스')),
Chip(label: Text('객체')),
Chip(label: Text('완료 상태'))
],
),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('클래스 → 객체 생성 → 메서드 호출 → 화면 표시')
],
)
],
),
)
클래스 활용 결과
클래스객체완료 상태
클래스 → 객체 생성 → 메서드 호출 → 화면 표시
메서드
클래스 안에 들어 있는 함수입니다. 객체의 값을 읽거나 객체와 관련된 행동을 표현합니다.
언제 쓰나: 데이터와 강하게 연결된 동작일 때 클래스 안에 둡니다.
Flutter에서: 모델의 copyWith, fromJson, toJson 같은 메서드가 대표적입니다.
class Lesson {
const Lesson({required this.title, this.done = false});
final String title;
final bool done;
// 기존 객체는 그대로 두고 완료 상태만 바꾼 새 객체를 만듭니다.
Lesson complete() {
return Lesson(title: title, done: true);
}
}
Container(
padding: const EdgeInsets.all(20),
decoration: BoxDecoration(
color: Colors.white,
border: Border.all(color: const Color(0xFFDCE6EF)),
borderRadius: BorderRadius.circular(8),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
decoration: BoxDecoration(
color: const Color(0xFFEEF7FB),
borderRadius: BorderRadius.circular(8),
),
child: const Text(
'클래스 활용 결과',
style: TextStyle(fontSize: 20, fontWeight: FontWeight.w900),
),
),
Wrap(
spacing: 8,
runSpacing: 8,
children: [
Chip(label: Text('클래스')),
Chip(label: Text('객체')),
Chip(label: Text('완료 상태'))
],
),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('클래스 → 객체 생성 → 메서드 호출 → 화면 표시')
],
)
],
),
)
클래스 활용 결과
클래스객체완료 상태
클래스 → 객체 생성 → 메서드 호출 → 화면 표시
상세 설명
더 알아보기
서버 응답을 Map 그대로 화면까지 넘기면 키 이름 오타나 타입 오류를 늦게 발견합니다. 모델 클래스로 변환하면 화면 코드는 title, done 같은 필드를 안전하게 읽을 수 있습니다.
상태 변경이 필요한 모델은 원본 객체를 직접 바꾸기보다 copyWith처럼 새 객체를 만드는 방식이 추적하기 쉽습니다. 이 패턴은 Provider, Riverpod, Bloc 같은 상태관리에서도 자주 쓰입니다.
코드
예제
// 강의 하나를 표현하는 불변 모델입니다.
class Lesson {
const Lesson({
required this.id,
required this.title,
this.done = false,
});
// id는 서버나 로컬 DB에서 강의를 구분하는 고유값입니다.
final String id;
// title은 화면에 표시할 강의 제목입니다.
final String title;
// done은 완료 여부이며, 기본값은 false입니다.
final bool done;
// copyWith는 기존 객체를 직접 바꾸지 않고 새 객체를 만들어 줍니다.
Lesson copyWith({String? title, bool? done}) {
return Lesson(
// id는 바꾸지 않으므로 기존 값을 그대로 사용합니다.
id: id,
// 새 title이 들어오면 새 값을 쓰고, 아니면 기존 값을 유지합니다.
title: title ?? this.title,
// 새 done이 들어오면 새 값을 쓰고, 아니면 기존 값을 유지합니다.
done: done ?? this.done,
);
}
}
// 원본 객체입니다.
final lesson = Lesson(id: 'dart-1', title: '클래스');
// 완료 처리된 새 객체입니다. lesson 자체는 바뀌지 않습니다.
final completed = lesson.copyWith(done: true);
Container(
padding: const EdgeInsets.all(20),
decoration: BoxDecoration(
color: Colors.white,
border: Border.all(color: const Color(0xFFDCE6EF)),
borderRadius: BorderRadius.circular(8),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
decoration: BoxDecoration(
color: const Color(0xFFEEF7FB),
borderRadius: BorderRadius.circular(8),
),
child: const Text(
'클래스 활용 결과',
style: TextStyle(fontSize: 20, fontWeight: FontWeight.w900),
),
),
Wrap(
spacing: 8,
runSpacing: 8,
children: [
Chip(label: Text('클래스')),
Chip(label: Text('객체')),
Chip(label: Text('완료 상태'))
],
),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('클래스 → 객체 생성 → 메서드 호출 → 화면 표시')
],
)
],
),
)
클래스 활용 결과
클래스객체완료 상태
클래스 → 객체 생성 → 메서드 호출 → 화면 표시
주의 사항
실무에서 확인할 점
- 상태 모델은 가능하면 final 필드를 가진 불변 객체로 시작하세요.
- copyWith는 일부 값만 바꾼 새 객체를 만들 때 유용합니다.
- 생성자에서 required를 활용하면 잘못된 객체 생성을 줄일 수 있습니다.
다음 단계
실습 체크리스트
필드 선언생성자 작성메서드 작성copyWith 개념 이해
- 출처세부 기준과 최신 변경 사항을 확인할 수 있습니다.
- Flutter API Reference클래스, 메서드, 생성자 세부 정의를 확인합니다.
- Dart languageDart 문법 자체가 궁금할 때 함께 봅니다.