Flutter error
Cannot extract closure as method, it references 1 external variable. 에러는 종종 클로저(익명 함수) 내부에서 외부 변수를 참조할 때 발생할 수 있습니다.
이 에러 메시지는 클로저가 외부 스코프에 있는 변수를 참조하고 있어서 클로저를 별도의 메서드로 추출하기 어렵다는 것을 의미합니다. 클로저는 주변 환경의 변수를 "캡처"할 수 있는데, 이 과정에서 클로저는 해당 변수에 대한 참조를 저장합니다. 만약 이 클로저를 클래스의 메서드로 추출하려고 할 때, 클로저가 참조하는 외부 변수가 클래스의 맥락에 없기 때문에 문제가 발생할 수 있습니다.
▣ 에러 현상 :
flutter 사용 중, Extract Method 로 내부 로직을 분리하는 중 발생.
▣ 에러 원인 :
클로저 내부에서 외부 스코프의 변수를 참조하고 있는 경우, 독립된 메소드로 추출 불가.
▣ 해결 방법 :
외부 변수를 참조하지 않게 외부 변수 제거하거나, 파라미터값으로 변수를 전달 받는 형태로 변경 .
ex) javascript 예제
// 에러발생
function outer() {
const x = 1;
function inner() {
return x;
}
return inner;
}
const closure = outer();
function outer() {
const x = 1;
function inner(x) {
return x;
}
return inner;
}
const closure = outer();
closure(1); // works!
ex) flutter 예제
// Navi push 기능 추출 실패
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const TodayPage(),
));
},
// 변수로 변경
onPressed: () {
_navigator(context);
},
'IT-FrontEnd > Flutter' 카테고리의 다른 글
flutter positional parameter constructor (0) | 2023.11.08 |
---|---|
flutter - Hive (0) | 2023.11.06 |
flutter Local Alarm Notification install & code (0) | 2023.11.02 |
Flutter StateLessWidget, StatefulWidget (1) | 2023.10.29 |
flutter build.gradle (0) | 2023.10.26 |