스프레드에서 불필요한 'toList' 사용

스프레드에서 불필요한 'toList' 사용 (unnecessary_to_list_in_spreads)

이 문서는 Dart 분석기(analyzer)가 만들어 내는 unnecessary_to_list_in_spreads 진단(diagnostic)에 대해 설명해요. 스프레드 연산자를 적용하기 직전에 IterableList로 바꾸려고 toList를 사용할 때 분석기가 이 진단을 알려 줘요. 스프레드 연산자는 어떤 Iterable에도 적용할 수 있기 때문에 굳이 변환할 필요가 없거든요.

출처: unnecessary_to_list_in_spreads

본문

설명

분석기는 스프레드 연산자를 리스트에 적용하기 직전에 IterableList로 변환하려고 toList를 사용하면 이 진단을 만들어 내요. 스프레드 연산자는 어떤 Iterable에도 적용할 수 있으므로, toList로 변환하는 과정이 전혀 필요 없어요.

예시

다음 코드는 map의 결과에 대해 toList를 호출하는데, 그 결과는 스프레드 연산자를 바로 적용할 수 있는 Iterable이기 때문에 이 진단을 만들어 내요.

List toLowercase(List strings) {
  return [...strings.map((String s) => s.toLowerCase()).toList()];
}

일반적인 해결 방법

toList 호출을 제거해 주세요.

List toLowercase(List strings) {
  return [...strings.map((String s) => s.toLowerCase())];
}

더 알아보기