민프

[Flutter Error] Don't use 'BuildContext's across async gaps. Try rewriting the code to not reference the 'BuildContext' 본문

[Flutter Error]

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

민프야 2023. 10. 27. 09:29

개발을 하다가

Don't use 'BuildContext's across async gaps. Try rewriting the code to not reference the 'BuildContext'

라는 오류 경고를 보았습니다.

 

코드는 아래와 같습니다.

 Future<void> success(BuildContext context) async {
.
.
.
    
    
    // API 호출 수행
    try {
      await postQuestionnaire(jsonStr);

      Navigator.pop(context); // 로딩 다이얼로그 닫기
      Navigator.pushReplacement(
        context,
        MaterialPageRoute(builder: (context) => const RehabilitationExercisePage()),
      );
    } catch (e) {
      // API 호출 실패, 다이얼로그 닫고 오류 표시
      Navigator.pop(context); // 로딩 다이얼로그 닫기
      // 필요하다면 오류 메시지나 다이얼로그 표시
    }
  }

문제

공식홈페이지에 따르면  BuildContext를 비동기 간격(예: 비동기 함수 호출)을 거쳐 사용하는 것은 추천하지 않는다고 합니다.

이유로는 BuildContext를 저장해 두었다가 나중에 사용하는 것은 앱 크래시로 이어질 수 있는 오류를 쉽게 발생시킬 수 있기 때문입니다.

해결방안

비동기 후에 BuildContext를 사용할 때는 BuildContext의 mounted 속성을 반드시 체크해야 합니다.

이는 비동기 작업이 끝난 후에 해당 BuildContext가 여전히 위젯 트리에 속해 있는지 (즉, 유효한지)를 확인하기 위함입니다.

해결코드

 Future<void> success(BuildContext context) async {
.
.
.
    
    
    // API 호출 수행
    try {
      await postQuestionnaire(jsonStr);
     
      if (!context.mounted) return; // 추가된 코드
      Navigator.pop(context); 
      Navigator.pushReplacement(
        context,
        MaterialPageRoute(builder: (context) => const RehabilitationExercisePage()),
      );
    } catch (e) {
   
      Navigator.pop(context); 
  
    }
  }
Comments