map을 이용한 색상넣기 (16진수 곁들인)

pharmDev·2024년 12월 15일

Flutter에서 Map과 ScheduleCard를 활용한 일정 관리 UI 구성

안녕하세요! 이번 글에서는 Flutter에서 Map 자료구조와 map() 메서드를 활용해 동적으로 UI를 생성하는 방법을 소개하겠습니다. 아래 예제는 간단한 일정 관리 화면을 구현한 코드입니다. 해당 코드를 통해 Map과 Flutter 위젯을 유기적으로 사용하는 방법을 배워보세요. 😊


사용 사례

우리는 특정 날짜(selectedDay)를 키로, 그 날짜에 해당하는 일정 데이터를 값으로 가진 Map을 사용해 동적으로 일정 카드를 생성합니다.
만약 선택된 날짜에 일정이 있다면 해당 데이터를 가져와 위젯으로 변환하고, 일정이 없을 경우 빈 리스트를 반환합니다.


주요 코드

children: schedules.containsKey(selectedDay)
    ? schedules[selectedDay]!
        .map(
          (e) => ScheduleCard(
            startTime: e.startTime,
            endTime: e.endTime,
            color: Color(
              int.parse(
                'FF${e.color}',
                radix: 16,
              ),
            ),
            content: e.content,
          ),
        )
        .toList()
    : [],

코드 설명

1. 데이터 구조

  • schedules는 날짜(DateTime)를 키, 해당 날짜의 일정 리스트를 값으로 갖는 Map<DateTime, List<Schedule>>입니다.
  • selectedDay는 현재 사용자가 선택한 날짜를 나타냅니다.
Map<DateTime, List<Schedule>> schedules = {
  DateTime(2024, 12, 15): [
    Schedule(
      startTime: "10:00",
      endTime: "11:00",
      color: "FF5733",
      content: "Meeting with team",
    ),
    Schedule(
      startTime: "14:00",
      endTime: "15:00",
      color: "33FF57",
      content: "Doctor's appointment",
    ),
  ],
};

2. 선택된 날짜의 일정 확인

containsKey 메서드를 사용해 schedulesselectedDay 키가 있는지 확인합니다.

  • 키가 존재하면: 해당 키의 값(일정 리스트)을 가져옵니다.
  • 키가 존재하지 않으면: 빈 리스트를 반환하여 화면에 아무것도 렌더링하지 않습니다.
schedules.containsKey(selectedDay)

3. map() 메서드로 동적 위젯 생성

  • schedules[selectedDay]!는 선택된 날짜의 일정 리스트를 반환합니다.
  • 각 일정 데이터를 ScheduleCard 위젯으로 변환합니다.
.map(
  (e) => ScheduleCard(
    startTime: e.startTime,
    endTime: e.endTime,
    color: Color(
      int.parse(
        'FF${e.color}', // 16진수 색상 코드로 변환
        radix: 16,
      ),
    ),
    content: e.content,
  ),
)

ScheduleCard 위젯 구성

ScheduleCard는 일정의 시작 시간, 종료 시간, 색상, 그리고 내용을 표시하는 커스텀 위젯입니다.

class ScheduleCard extends StatelessWidget {
  final String startTime;
  final String endTime;
  final Color color;
  final String content;

  const ScheduleCard({
    required this.startTime,
    required this.endTime,
    required this.color,
    required this.content,
  });

  
  Widget build(BuildContext context) {
    return Container(
      margin: const EdgeInsets.symmetric(vertical: 8.0),
      padding: const EdgeInsets.all(16.0),
      decoration: BoxDecoration(
        color: color,
        borderRadius: BorderRadius.circular(8.0),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            '$startTime - $endTime',
            style: TextStyle(fontWeight: FontWeight.bold, color: Colors.white),
          ),
          const SizedBox(height: 8),
          Text(
            content,
            style: TextStyle(color: Colors.white),
          ),
        ],
      ),
    );
  }
}

4. 색상 변환

  • 일정 데이터에서 색상 값은 문자열 형태로 저장되어 있습니다(e.g., "FF5733").
  • 이 값을 Flutter에서 사용하는 Color 객체로 변환하려면 16진수로 파싱해야 합니다.
  • int.parseColor를 활용해 변환을 수행합니다.
color: Color(
  int.parse(
    'FF${e.color}', // 불투명도(FF)를 추가한 16진수 색상 문자열
    radix: 16,      // 16진수로 파싱
  ),
),

5. 결과 UI

ListViewColumnchildren 속성에 변환된 ScheduleCard 리스트를 전달하면, 선택한 날짜의 일정이 화면에 표시됩니다.

ListView(
  children: schedules.containsKey(selectedDay)
      ? schedules[selectedDay]!
          .map(
            (e) => ScheduleCard(
              startTime: e.startTime,
              endTime: e.endTime,
              color: Color(
                int.parse('FF${e.color}', radix: 16),
              ),
              content: e.content,
            ),
          )
          .toList()
      : [],
),

전체 코드

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  final Map<DateTime, List<Schedule>> schedules = {
    DateTime(2024, 12, 15): [
      Schedule(
        startTime: "10:00",
        endTime: "11:00",
        color: "FF5733",
        content: "Meeting with team",
      ),
      Schedule(
        startTime: "14:00",
        endTime: "15:00",
        color: "33FF57",
        content: "Doctor's appointment",
      ),
    ],
  };

  final DateTime selectedDay = DateTime(2024, 12, 15);

  
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('Schedule List')),
        body: ListView(
          children: schedules.containsKey(selectedDay)
              ? schedules[selectedDay]!
                  .map(
                    (e) => ScheduleCard(
                      startTime: e.startTime,
                      endTime: e.endTime,
                      color: Color(
                        int.parse('FF${e.color}', radix: 16),
                      ),
                      content: e.content,
                    ),
                  )
                  .toList()
              : [Text('No schedules available')],
        ),
      ),
    );
  }
}

class Schedule {
  final String startTime;
  final String endTime;
  final String color;
  final String content;

  Schedule({
    required this.startTime,
    required this.endTime,
    required this.color,
    required this.content,
  });
}

class ScheduleCard extends StatelessWidget {
  final String startTime;
  final String endTime;
  final Color color;
  final String content;

  const ScheduleCard({
    required this.startTime,
    required this.endTime,
    required this.color,
    required this.content,
  });

  
  Widget build(BuildContext context) {
    return Container(
      margin: const EdgeInsets.symmetric(vertical: 8.0),
      padding: const EdgeInsets.all(16.0),
      decoration: BoxDecoration(
        color: color,
        borderRadius: BorderRadius.circular(8.0),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            '$startTime - $endTime',
            style: TextStyle(fontWeight: FontWeight.bold, color: Colors.white),
          ),
          const SizedBox(height: 8),
          Text(
            content,
            style: TextStyle(color: Colors.white),
          ),
        ],
      ),
    );
  }
}

결론

이번 포스트에서는 Mapmap() 메서드를 활용해 동적으로 UI를 구성하는 방법을 배웠습니다. 특히, Flutter 앱에서 Map을 사용하면 데이터 구조화와 UI 동적 생성을 효율적으로 처리할 수 있습니다. 위 코드를 확장해 달력, 일정 관리 앱 등으로 발전시켜 보세요! 😊

profile
코딩을 배우는 초보

0개의 댓글