Flutter에서 Mapping 사용하기

pharmDev·2024년 12월 14일

Dart의 Map키(Key)값(Value)의 쌍으로 데이터를 저장하는 컬렉션입니다. Map은 데이터를 효율적으로 검색, 추가, 삭제할 수 있도록 설계되어 있으며, 키를 사용해 값을 참조합니다.


1. Map의 기본 구조

void main() {
  // Map 선언
  Map<String, int> scores = {
    'Alice': 85,
    'Bob': 92,
    'Charlie': 78,
  };

  print(scores['Alice']); // 출력: 85
}

키와 값의 특징:

  1. 키 (Key):

    • 고유해야 하며 중복될 수 없습니다.
    • 데이터를 식별하는 데 사용됩니다.
    • Dart에서 기본적으로 String, int, 또는 커스텀 객체를 사용할 수 있습니다.
  2. 값 (Value):

    • 키에 매핑된 데이터입니다.
    • 어떤 타입이든 될 수 있습니다.

2. Map의 주요 메서드

void main() {
  Map<String, int> scores = {
    'Alice': 85,
    'Bob': 92,
    'Charlie': 78,
  };

  // 키와 값 가져오기
  print(scores.keys);   // 출력: (Alice, Bob, Charlie)
  print(scores.values); // 출력: (85, 92, 78)

  // 요소 추가
  scores['Diana'] = 88;
  print(scores); // 출력: {Alice: 85, Bob: 92, Charlie: 78, Diana: 88}

  // 요소 삭제
  scores.remove('Charlie');
  print(scores); // 출력: {Alice: 85, Bob: 92, Diana: 88}

  // 특정 키 확인
  print(scores.containsKey('Alice')); // 출력: true

  // 특정 값 확인
  print(scores.containsValue(92)); // 출력: true
}

3. 키와 값 활용

키-값 순회 (forEach)

Map에서 모든 키와 값을 순회하며 사용할 수 있습니다.

void main() {
  Map<String, int> scores = {
    'Alice': 85,
    'Bob': 92,
    'Charlie': 78,
  };

  scores.forEach((key, value) {
    print('$key scored $value');
  });

  // 출력:
  // Alice scored 85
  // Bob scored 92
  // Charlie scored 78
}

4. map을 사용한 키-값 변환

예: 점수에 따라 합격/불합격 변환

void main() {
  Map<String, int> scores = {
    'Alice': 85,
    'Bob': 92,
    'Charlie': 78,
  };

  // 점수에 따라 합격/불합격 표시
  Map<String, String> results = scores.map((key, value) {
    return MapEntry(key, value >= 80 ? 'Pass' : 'Fail');
  });

  print(results); // 출력: {Alice: Pass, Bob: Pass, Charlie: Fail}
}

코드 설명:

  1. map 메서드:
    • 기존 Map을 기반으로 새 Map 생성.
    • MapEntry를 반환해 키와 값을 재정의.

5. Flutter에서 Map 활용

예: 키-값으로 동적 위젯 생성

시나리오:

점수 데이터를 받아 이름과 점수를 각각 Row에 정렬.

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  final Map<String, int> scores = {
    'Alice': 85,
    'Bob': 92,
    'Charlie': 78,
    'Diana': 88,
  };

  
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('Scores')),
        body: ListView(
          children: scores.entries.map((entry) {
            return Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(entry.key, style: TextStyle(fontSize: 18)),
                Text(entry.value.toString(), style: TextStyle(fontSize: 18)),
              ],
            );
          }).toList(),
        ),
      ),
    );
  }
}

코드 설명:

  1. scores.entries:

    • Map의 키와 값을 포함하는 MapEntry 리스트를 반환.
  2. map으로 변환:

    • MapEntryRow 위젯으로 변환.
  3. 결과:

    • 이름과 점수가 각각 정렬된 UI 생성.

6. Map의 고급 활용

예: 중첩된 Map 구조 처리

시나리오:

사용자 정보와 점수를 포함한 중첩된 데이터를 처리.

void main() {
  Map<String, Map<String, dynamic>> userData = {
    'Alice': {'age': 22, 'score': 85},
    'Bob': {'age': 24, 'score': 92},
    'Charlie': {'age': 19, 'score': 78},
  };

  userData.forEach((name, details) {
    print('$name is ${details['age']} years old and scored ${details['score']}');
  });

  // 출력:
  // Alice is 22 years old and scored 85
  // Bob is 24 years old and scored 92
  // Charlie is 19 years old and scored 78
}

요약

  • Map의 키와 값:
    • 키: 데이터를 식별하는 고유 값.
    • 값: 키에 매핑된 데이터.
  • 사용 방법:
    • 키와 값을 순회: forEach, map.
    • 데이터를 조작하거나 변환: map 메서드.
  • Flutter에서 활용:
    • Map 데이터를 기반으로 동적 UI 생성.

Map은 데이터를 구조적으로 관리하면서 Flutter 애플리케이션에서 UI를 생성하거나 상태를 관리하는 데 강력한 도구가 됩니다. 💡

Dart의 map은 리스트나 맵과 같은 컬렉션 데이터를 조작하고 변환하는 데 유용합니다. Flutter에서는 데이터를 UI 요소로 변환하는 데 자주 활용됩니다. 아래는 다양한 예제를 통해 map을 사용하는 방법을 쉽게 이해할 수 있도록 설명합니다.


1. 쉬운 예: 리스트 요소 변환

시나리오:

숫자 리스트를 받아 각 숫자에 2를 곱한 새로운 리스트 생성.

void main() {
  List<int> numbers = [1, 2, 3, 4, 5];

  // map을 사용하여 리스트의 각 요소를 변환
  List<int> doubled = numbers.map((number) => number * 2).toList();

  print(doubled); // 출력: [2, 4, 6, 8, 10]
}

코드 설명:

  1. map은 리스트의 각 요소를 순회하며 변환 작업을 수행.
  2. 반환된 결과는 Iterable이므로 toList()를 호출해 리스트로 변환.

2. 어려운 예: 객체 변환 및 필터링

시나리오:

사용자 리스트에서 이름과 나이를 특정 형식으로 변환, 나이가 18세 이상인 사용자만 포함.

void main() {
  List<Map<String, dynamic>> users = [
    {'name': 'Alice', 'age': 22},
    {'name': 'Bob', 'age': 17},
    {'name': 'Charlie', 'age': 19},
  ];

  // 필터링과 변환
  List<String> adultUsers = users
      .where((user) => user['age'] >= 18) // 18세 이상 필터링
      .map((user) => '${user['name']} (${user['age']} years old)') // 문자열 변환
      .toList();

  print(adultUsers); // 출력: ['Alice (22 years old)', 'Charlie (19 years old)']
}

코드 설명:

  1. where: 조건에 맞는 요소를 필터링.
  2. map: 필터링된 데이터를 변환.
  3. 결과 리스트는 이름과 나이가 포함된 문자열 형태.

3. Map과 Row를 혼합한 예

Flutter에서 map을 사용하여 리스트 데이터를 동적으로 위젯으로 변환해 Row에 배치할 수 있습니다.


예: Row에 동적으로 버튼 추가

시나리오:

이름 리스트를 받아 버튼으로 변환하여 수평으로 정렬. 각 버튼 클릭 시 이름 출력.

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  final List<String> names = ['Alice', 'Bob', 'Charlie', 'Diana'];

  
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('Map and Row Example')),
        body: Center(
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: names
                .map((name) => Padding(
                      padding: const EdgeInsets.symmetric(horizontal: 8.0),
                      child: ElevatedButton(
                        onPressed: () {
                          print('Clicked: $name');
                        },
                        child: Text(name),
                      ),
                    ))
                .toList(),
          ),
        ),
      ),
    );
  }
}

코드 설명:

  1. names.map:
    리스트의 각 이름을 버튼 위젯으로 변환.

    names.map((name) => ElevatedButton(...))
  2. Padding:
    버튼 간격 조정.

  3. Row:
    Row 위젯으로 버튼을 수평 정렬.

    • MainAxisAlignment.center: 중앙 정렬.
  4. onPressed:
    버튼 클릭 시 이름 출력.


응용: 색상별 컨테이너 생성

시나리오:

색상 리스트를 받아 색상 블록을 Row로 정렬.

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  final List<Map<String, dynamic>> colors = [
    {'name': 'Red', 'color': Colors.red},
    {'name': 'Green', 'color': Colors.green},
    {'name': 'Blue', 'color': Colors.blue},
    {'name': 'Yellow', 'color': Colors.yellow},
  ];

  
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('Colors Row Example')),
        body: Center(
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: colors
                .map((colorData) => GestureDetector(
                      onTap: () {
                        print('Clicked: ${colorData['name']}');
                      },
                      child: Container(
                        width: 50,
                        height: 50,
                        color: colorData['color'],
                      ),
                    ))
                .toList(),
          ),
        ),
      ),
    );
  }
}

코드 설명:

  1. 색상 데이터 맵 리스트:
    각 색상 이름과 색상 값을 포함하는 맵 리스트.

  2. map으로 컨테이너 생성:
    각 맵 데이터를 기반으로 색상이 적용된 Container 생성.

  3. 클릭 이벤트 처리:
    GestureDetector로 클릭 이벤트를 처리.

  4. Row 정렬:
    색상 블록을 수평으로 정렬.


요약

  1. 쉬운 예: 데이터를 단순 변환.
  2. 어려운 예: 필터링과 데이터 변환을 결합.
  3. Flutter에서의 활용: Rowmap을 결합해 UI 요소를 동적으로 생성.
  4. 추가로 Column 등 다른 레이아웃과 조합하여 다양한 방식으로 활용 가능.

이런 방식으로 map을 사용하면 데이터 중심의 UI를 효율적으로 구현할 수 있습니다. 🚀

profile
코딩을 배우는 초보

0개의 댓글