[에러 상황]
회사에서 프로젝트를 진행 하던 중, 리스트 뷰에서 GetXController를 update하는 구문을 호출하였더니, 에러가 발생했다
child: ListView.builder(
itemCount: controller.enterpriseList.length,
itemBuilder: (context, index) {
if (controller.hasMore == true && !controller.isLoading &&
index == controller.enterpriseList.length - 1)
// 이렇게 바로 실행하면 에러
SdmSearchController.find().search(searchTerm: controller.searchTerm ?? '');
return Center(
child: CircularProgressIndicator(
color: AppTheme.colors.pink,
strokeWidth: 2,
));
}
- 에러 발생한 이유
- 무한 루프나 논리 충돌이 발생할 수 있어서 Flutter가 예외로 막아 놓았기 때문- 해결법
- Future.microtask()로 감싸기- 에러가 안 나는 이유
Flutter의 build phase가 끝난 직후(=마이크로태스크 큐)에 controller.update()를 실행하게 되기 때문
🔍 개념 정리
build() 중에 update() 호출 -> 에러 발생 : 현재 화면을 그리고 있는 중에 다시 그리라고 하면 안 됨
Future.microtask(() => controller.update()) : build가 끝난 직후, 마이크로태스크 큐에 실행되니까 안전
📌 Future.microtask()
지금 실행중인 동기 작업이 끝나자마자 바로 실행되는 비동기 함수
즉, build() 함수가 지금 당장 실행되고 있는 중이라면,
controller.update(); // 에러 발생
하지만,
Future.microtask(() => controller.update()); // 저장해놨다가 바로 실행
Flutter가 build phase를 마치고 난 직후, 즉 다음 이벤트 루프 사이클 전에 update()를 실행하기 때문에 안전하게 UI를 갱신할 수 있다.