본문 바로가기
Flutter

Flutter에서 TableCalendar를 활용한 캘린더 UI 구현

by 안될개발 2025. 1. 26.

Flutter에서 TableCalendar를 활용한 캘린더 UI 구현

Flutter에서 TableCalendar를 활용한 캘린더 UI 구현

Flutter는 다양한 플러그인을 통해 강력한 UI와 기능을 제공합니다. 그중 table_calendar는 사용자 정의가 가능한 캘린더 위젯을 쉽게 구현할 수 있도록 돕는 인기 있는 패키지입니다. 이번 글에서는 table_calendar의 주요 기능과 사용법, 그리고 고급 커스터마이징 방법까지 알아보겠습니다.


1. TableCalendar 설치 및 초기 설정

먼저 table_calendar 패키지를 프로젝트에 추가합니다.

1.1 패키지 추가

flutter pub add table_calendar

1.2 기본 사용 설정

pubspec.yaml 파일에 패키지가 추가되었는지 확인한 후, 캘린더를 표시할 화면에 아래 코드를 추가합니다.

import 'package:flutter/material.dart';
import 'package:table_calendar/table_calendar.dart';

class CalendarPage extends StatefulWidget {
  @override
  _CalendarPageState createState() => _CalendarPageState();
}

class _CalendarPageState extends State<CalendarPage> {
  DateTime _focusedDay = DateTime.now();
  DateTime? _selectedDay;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('TableCalendar Example'),
      ),
      body: TableCalendar(
        firstDay: DateTime.utc(2000, 1, 1),
        lastDay: DateTime.utc(2100, 12, 31),
        focusedDay: _focusedDay,
        selectedDayPredicate: (day) => isSameDay(_selectedDay, day),
        onDaySelected: (selectedDay, focusedDay) {
          setState(() {
            _selectedDay = selectedDay;
            _focusedDay = focusedDay;
          });
        },
        calendarFormat: CalendarFormat.month,
      ),
    );
  }
}

2. 주요 기능 살펴보기

2.1 날짜 선택 및 포커싱

onDaySelected 콜백을 사용하여 사용자가 선택한 날짜와 포커스된 날짜를 처리할 수 있습니다. 위 예제에서 setState를 통해 선택한 날짜를 업데이트하고, 관련 로직을 추가하여 동작을 확장할 수 있습니다.

2.2 캘린더 형식 전환

calendarFormat 속성을 활용해 월간, 주간, 이중 주간 보기 등 다양한 형식을 제공합니다. 형식 변경 이벤트를 처리하려면 onFormatChanged를 활용합니다.

onFormatChanged: (format) {
  setState(() {
    _calendarFormat = format;
  });
},

3. 커스터마이징

3.1 스타일 변경

캘린더의 색상, 텍스트 스타일 등을 변경하려면 CalendarStyle과 HeaderStyle을 사용합니다.

TableCalendar(
  calendarStyle: CalendarStyle(
    todayDecoration: BoxDecoration(
      color: Colors.blue,
      shape: BoxShape.circle,
    ),
    selectedDecoration: BoxDecoration(
      color: Colors.orange,
      shape: BoxShape.circle,
    ),
    weekendTextStyle: TextStyle(color: Colors.red),
  ),
  headerStyle: HeaderStyle(
    formatButtonVisible: false,
    titleCentered: true,
  ),
);

3.2 커스텀 이벤트

특정 날짜에 이벤트를 표시하려면 Map 자료구조를 사용해 데이터를 연결합니다.

final Map<DateTime, List<String>> _events = {
  DateTime(2023, 11, 1): ['Event A', 'Event B'],
  DateTime(2023, 11, 5): ['Event C'],
};

TableCalendar(
  eventLoader: (day) {
    return _events[day] ?? [];
  },
);

eventLoader를 사용해 특정 날짜에 해당하는 이벤트를 반환합니다.

3.3 커스텀 빌더 사용

CalendarBuilders를 사용하여 날짜, 헤더, 이벤트 등을 커스터마이징할 수 있습니다.

TableCalendar(
  calendarBuilders: CalendarBuilders(
    markerBuilder: (context, day, events) {
      if (events.isNotEmpty) {
        return Positioned(
          right: 1,
          bottom: 1,
          child: Container(
            decoration: BoxDecoration(
              color: Colors.blue,
              shape: BoxShape.circle,
            ),
            width: 8,
            height: 8,
          ),
        );
      }
      return null;
    },
  ),
);

4. 고급 사용법

4.1 데이터베이스 연동

SQLite나 Firebase와 연동하여 이벤트 데이터를 저장하고 로드하는 방식으로 캘린더를 확장할 수 있습니다.

4.2 날짜 범위 선택

날짜 범위를 선택하려면 rangeStartDay, rangeEndDay 속성을 사용합니다.

TableCalendar(
  rangeStartDay: _rangeStart,
  rangeEndDay: _rangeEnd,
  onRangeSelected: (start, end, focusedDay) {
    setState(() {
      _rangeStart = start;
      _rangeEnd = end;
      _focusedDay = focusedDay;
    });
  },
);

5. 결론

table_calendar는 Flutter에서 캘린더 UI를 손쉽게 구현할 수 있는 강력한 도구입니다.

기본적인 날짜 선택 기능부터 고급 커스터마이징, 이벤트 표시 및 데이터 연동까지 다양한 활용 사례를 제공합니다.