[Flutter] Dart 문법 4 - 컬렉션, 반복문

류재성's avatar
Apr 12, 2024
[Flutter] Dart 문법 4 - 컬렉션, 반복문
 

1. List

 
💡
List 는 데이터의 중복이 가능하고 순서가 있는 자료를 담는 컬렉션이다. 자료는 순차적으로 index 번호를 생성하여 쌓이게 된다.
 
void main() { List<int> nums = [1, 2, 3, 4]; // 데이터 중복 가능하고 순서가 있는 자료 데이터 print(nums[0]); print(nums[1]); print(nums[2]); print(nums[3]); }
 
notion image
 

2. Map

 
💡
Map 은 키(key)와 값(value)의 쌍으로 이루어진 컬렉션이다. List 는 index 번호로 찾지만, map 은 키로 값을 찾아야 한다.
 
void main() { Map<String, dynamic> user = { "id": 1, // 키 : 값 "username": "cos" print(user["id"]); print(user["username"]); }
 
notion image
 

3. Set

 
💡
집합을 표현하는 컬렉션이다. List와 다르게 데이터의 중복을 허용하지 않고, 순서가 없다.
 
import 'dart:math'; void main() { Set<int> lotto = {}; Random r = Random(); lotto.add(r.nextInt(45) + 1); lotto.add(r.nextInt(45) + 1); lotto.add(r.nextInt(45) + 1); lotto.add(r.nextInt(45) + 1); lotto.add(r.nextInt(45) + 1); lotto.add(r.nextInt(45) + 1); print(lotto); //toList를 사용하면 List 타입으로 변경된다. List<int> lottoList = lotto.toList(); // sort 메서드로 정렬 lottoList.sort(); print(lottoList); }
 
notion image
 

4. 반복문

 

4.1. for문

 
void main() { var list = [1, 2, 3, 4]; for (int i = 0; i < list.length; i++) { print(list[i]); } }
 
notion image
 

4.2. map 함수

 
💡
반복되는 값을 하나씩 변형하기 위해 사용한다.
void main() { var chobob = ["새우초밥", "광어초밥", "연어초밥"]; var chobobChange = chobob.map((e) => "간장_" + e); print(chobobChange); }
 
notion image
 

4.3. where 연산자

 
💡
반복되는 값에서 필요 없는 값을 필터링하거나 필요한 값을 찾을 때 사용한다.
 
void main() { var chobob = ["새우초밥", "광어초밥", "연어초밥"]; var chobobChange = chobob.where((e) => e != "광어초밥"); print(chobobChange); }
notion image
Share article
RSSPowered by inblog