728x90
dart의 map에 대해서 알아보겠습니당~~!
api.dart.dev/stable/2.10.5/dart-core/Iterable/map.html
flutter 로 개발하면서 map 함수를 사용하는 순간이 굉장히 많습니다.
Iterable<T> map<T>(T f(E e)) => MappedIterable<E, T>(this, f);
공식 문서에는 다음과 같이 설명이 되어 있네요!
Returns a new lazy Iterable with elements that are created by calling f on each element of this Iterable in iteration order. |
해석해보면, 새로운 lazy iteralbe 요소를 반환하고 각각의 요소를 f로 호출한다는 것인데요,
간단한 예제를 통해 한번 살펴봅시다!
List<int> list = [1,2,3,4];
List<int> newList = [];
list.map((value) {
newList.add(value);
return value;
}
만약, list를 map 해서 각 요소를 newList에 추가하면 어떤 결과가 나올까요?
당연히 list 변수의 값들이 newList에 있을 것이라고 생각할 텐데,, 답은 [] 빈 리스트인 상태입니다!
왜 그럴까요? 이에 대한 답은 map method에 대한 정의를 보면 알 수 있는데요..!
반환 형태로 lazy iterable을 가지고 있기 때문입니다!
The methods that return another Iterable (like map and where) are all lazy - they will iterate the original (as necessary) every time the returned iterable is iterated, and not before. |
따라서 우리가 원하는 결과인, list 값을 map 함수를 통해 newList로 옮기려면,
map에서 리턴해주는 iterable을 사용해서 옮겨보면 우링가 원하는 값이 정상적으로 반환되는 것을 확인 할 수 있습니다.
List<int> list = [1,2,3,4];
Iterable<int> newIterable = list.map((value) {
return value;
}
newIterable.toList();
'✏️ > Flutter' 카테고리의 다른 글
[flutter][ios] kakao_flutter_sdk 0.6.0 로그인 문제 (+ 네이버 로그인) - flutter 1.xx version (0) | 2021.05.13 |
---|---|
[flutter] freezed ,,! 앞으로 친해지자!!! (0) | 2021.04.19 |
[flutter] CocoaPods install error - `.symlinks/plugins/~ (0) | 2021.04.15 |
[flutter] ios 프로젝트 설정 오류 - Runner config, CocoaPods (0) | 2021.04.15 |
[flutter] The application's Info.plist does not contain CFBundleVersion. 에러 해결 방법 (0) | 2021.04.15 |