본문 바로가기
컴퓨터언어/Dart&Flutter

[flutter] List

by 인턴개구리 2023. 9. 23.

List

void main(){
  //리스트 형식
  List<String> alphabetList = ["aa","bb","cc"];
}

1. add() -> 값을 마지막에 추가

//1. add 함수
  alphabetList.add("dd"); // 결과 : ["aa","bb","cc","dd"]
  
  print(alphabetList[3]); // 결과 : "dd"
  print(alphabetList.length); // 결과 : 4

2. where() 함수 : List에 있는 값을 순회하며 조건에 맞는 값을 필터링

//2. where() 함수 : List에 있는 값을 순회하며 조건에 맞는 값을 필터링
  final newList = alphabetList.where(
    (str) => str == "aa" || str == "cc"
  ); //aa와 cc만 추출
  
  print(newList); // 결과 : (aa, cc) -> 이터러블로 반환
  print(newList.toList());// 결과 : [aa, cc] -> 이터러블을 List로 다시 변환

3.map()함수 : List의 값들을 순회하며 값을 변경 

//3.map()함수 : List의 값들을 순회하며 값을 변경
	final newAlphabetList = alphabetList.map(
  (str) => 'Alphabet $str' 
  );
  print(newAlphabetList.toList()); //결과 : [alphabet aa, alphabet bb, alphabet cc, alphabet dd]

4. reduce() 함수 : List를 순회하면서 값을 쌓아간다

//4. reduce() 함수 : List를 순회하면서 값을 쌓아간다 (List를 반환)
  final allAlphabets = alphabetList.reduce((value, element) => value + ' + '+ element); //리스트를 순회하면 값들을 더한다
  print(allAlphabets); //결과 : "aa + bb + cc + dd"
  print(allAlphabets.runtimeType); //결과 : String

5. fold()함수 : reduce()와 똑같으나 어떠한 타입도 가능

//5. fold()함수 : reduce()와 똑같으나 어떠한 타입도 가능
  final allAlphabetsFold = alphabetList.fold<int>(0, (value, element) => value + element.length); //알파벳 길이를 더한다
  print(allAlphabetsFold); //결과 : 8 => 2+2+2+2=8

 

참조 : [Must Have] 코드팩토리의 플러터 프로그래밍