Coding BGM ♬
 

[Flutter] Don't use 'BuildContext's across async gaps. Try rewriting the code to not reference the 'BuildContext' 해결방법

2023-11-29


사진: Unsplash 의 NEOM


1. 원인

 

비동기로 동작하는 코드에서 BuildContext를 사용해서 해당 문제가 발생하게 된다. 이는 widget의 비동기 동작 후에 정확인 mounted 되었는지 확인이 필요하며, 이후에 BuildContext를 호출해서 사용하라는 에러이다.


2. 해결 방법

 

해결 방법은 간단하다. 자신이 사용하는 비동기 함수에서 BuildContext  사용 전 mounted 가 되어있는지 확인하면 된다. 아래는 간단한 예제이며, if (!context.mounted) return; 를 통해서 현제의 context가 mounted  여부를 확인 할 수 있다.

 

void foo(BuildContext context) async {
  await someFuture();
  if (!context.mounted) return;
  Navigator.pop(context); // No warnings now
}

 

물론 아래와 같이 코드를 작성해도 되며, 똑같이 warings 문구는 없어진다.

 

void foo(BuildContext context) async {
  await someFuture();
  if (context.mounted) {
  	Navigator.pop(context); // No warnings now
  }else {
  	//else handling code
  }
}

3. 참고자료

https://stackoverflow.com/questions/68871880/do-not-use-buildcontexts-across-async-gaps

 

Do not use BuildContexts across async gaps

I have noticed a new lint issue in my project. Long story short: I need to use BuildContext in my custom classes flutter lint tool is not happy when this being used with aysnc method. Example:

stackoverflow.com


메인 이미지 출처 : 사진: UnsplashNEOM