Dart의 Map은 키(Key)와 값(Value)의 쌍으로 데이터를 저장하는 컬렉션입니다. Map은 데이터를 효율적으로 검색, 추가, 삭제할 수 있도록 설계되어 있으며, 키를 사용해 값을 참조합니다.
void main() {
// Map 선언
Map<String, int> scores = {
'Alice': 85,
'Bob': 92,
'Charlie': 78,
};
print(scores['Alice']); // 출력: 85
}
키 (Key):
String, int, 또는 커스텀 객체를 사용할 수 있습니다.값 (Value):
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
}
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
}
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}
}
map 메서드:Map을 기반으로 새 Map 생성.MapEntry를 반환해 키와 값을 재정의.점수 데이터를 받아 이름과 점수를 각각 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(),
),
),
);
}
}
scores.entries:
Map의 키와 값을 포함하는 MapEntry 리스트를 반환.map으로 변환:
MapEntry를 Row 위젯으로 변환.결과:
사용자 정보와 점수를 포함한 중첩된 데이터를 처리.
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
}
forEach, map.map 메서드.Map은 데이터를 구조적으로 관리하면서 Flutter 애플리케이션에서 UI를 생성하거나 상태를 관리하는 데 강력한 도구가 됩니다. 💡
Dart의 map은 리스트나 맵과 같은 컬렉션 데이터를 조작하고 변환하는 데 유용합니다. Flutter에서는 데이터를 UI 요소로 변환하는 데 자주 활용됩니다. 아래는 다양한 예제를 통해 map을 사용하는 방법을 쉽게 이해할 수 있도록 설명합니다.
숫자 리스트를 받아 각 숫자에 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]
}
map은 리스트의 각 요소를 순회하며 변환 작업을 수행.Iterable이므로 toList()를 호출해 리스트로 변환.사용자 리스트에서 이름과 나이를 특정 형식으로 변환, 나이가 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)']
}
where: 조건에 맞는 요소를 필터링.map: 필터링된 데이터를 변환.Flutter에서 map을 사용하여 리스트 데이터를 동적으로 위젯으로 변환해 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(),
),
),
),
);
}
}
names.map:
리스트의 각 이름을 버튼 위젯으로 변환.
names.map((name) => ElevatedButton(...))
Padding:
버튼 간격 조정.
Row:
Row 위젯으로 버튼을 수평 정렬.
MainAxisAlignment.center: 중앙 정렬.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(),
),
),
),
);
}
}
색상 데이터 맵 리스트:
각 색상 이름과 색상 값을 포함하는 맵 리스트.
map으로 컨테이너 생성:
각 맵 데이터를 기반으로 색상이 적용된 Container 생성.
클릭 이벤트 처리:
GestureDetector로 클릭 이벤트를 처리.
Row 정렬:
색상 블록을 수평으로 정렬.
Row와 map을 결합해 UI 요소를 동적으로 생성.Column 등 다른 레이아웃과 조합하여 다양한 방식으로 활용 가능.이런 방식으로 map을 사용하면 데이터 중심의 UI를 효율적으로 구현할 수 있습니다. 🚀