Menu
CoddyTech

습관 추적기: 하루 체크하기

Coddy Flutter 여정의 프로젝트 섹션에 포함된 레슨. 36개 중 30번째.

원을 탭하면 해당 날짜에 체크 표시가 되고, 다시 탭하면 체크가 지워집니다. 습관 데이터는 화면의 상태에 있지만, 원은 HabitCard 깊숙한 곳에서 그려집니다. 탭 이벤트는 데이터가 있는 곳까지 위로 전달되어야 합니다.

이것이 콜백을 사용해 상태를 상위로 끌어올리는 방법입니다. 화면이 변경을 관리합니다.

void _toggle(Habit habit, int day) {
  setState(() {
    habit.days[day] = !habit.days[day];
  });
}

각 카드에 함수 onToggle: (day) => _toggle(habit, day)를 전달합니다. 카드에서 이 함수의 타입은 void Function(int day)이며, 날짜를 나타내는 숫자를 받는 함수입니다. 각 원에는 일반적인 VoidCallback인 onTap: () => onToggle(i)가 전달되고, 이를 호출하는 GestureDetector로 Container를 감쌉니다.

!habit.days[day]는 bool 값을 뒤집습니다. true는 false가 되고 다시 반대가 되므로, 하나의 함수로 체크 표시와 체크 해제를 모두 처리할 수 있습니다.

challenge icon

챌린지

어려움

요일을 선택하세요:

  • 화면의 상태에 _toggle 메서드를 추가합니다
  • HabitCard에 void Function(int day) 유형의 필수 onToggle을 지정하고, (day) => _toggle(habit, day)를 전달합니다
  • DayCircle에 필수 VoidCallback onTap을 지정하고, 해당 Container를 GestureDetector로 감싼 다음 () => onToggle(i)를 전달합니다

직접 해보기

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.green),
      ),
      home: const HabitScreen(),
    );
  }
}

const List<String> dayNames = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];

class Habit {
  Habit(this.name, this.days);

  final String name;
  final List<bool> days;
}

class HabitScreen extends StatefulWidget {
  const HabitScreen({super.key});

  @override
  State<HabitScreen> createState() => _HabitScreenState();
}

class _HabitScreenState extends State<HabitScreen> {
  final List<Habit> _habits = [
    Habit('Drink water', [true, true, true, false, true, false, false]),
    Habit('Read 10 pages', [true, false, true, true, false, false, false]),
    Habit('Stretch', List.filled(7, false)),
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Habits')),
      body: ListView(
        padding: const EdgeInsets.fromLTRB(16, 8, 16, 88),
        children: [
          for (Habit habit in _habits) HabitCard(habit: habit),
        ],
      ),
    );
  }
}

class HabitCard extends StatelessWidget {
  const HabitCard({super.key, required this.habit});

  final Habit habit;

  @override
  Widget build(BuildContext context) {
    final textTheme = Theme.of(context).textTheme;
    return Card(
      margin: const EdgeInsets.only(top: 12),
      clipBehavior: Clip.antiAlias,
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(habit.name, style: textTheme.titleMedium),
            const SizedBox(height: 12),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                for (int i = 0; i < 7; i++) DayCircle(label: dayNames[i], done: habit.days[i]),
              ],
            ),
          ],
        ),
      ),
    );
  }
}

class DayCircle extends StatelessWidget {
  const DayCircle({super.key, required this.label, required this.done});

  final String label;
  final bool done;

  @override
  Widget build(BuildContext context) {
    final colors = Theme.of(context).colorScheme;
    return Container(
      width: 40,
      height: 40,
      alignment: Alignment.center,
      decoration: BoxDecoration(
        shape: BoxShape.circle,
        color: done ? colors.primary : colors.surfaceContainerHighest,
      ),
      child: Text(
        label,
        style: TextStyle(
          fontSize: 11,
          fontWeight: FontWeight.bold,
          color: done ? colors.onPrimary : colors.onSurfaceVariant,
        ),
      ),
    );
  }
}
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

프로젝트의 모든 레슨

직접 연습해 보세요: 온라인 Flutter 컴파일러