본문 바로가기
개발노트/Flutter

[Flutter] addPostFrameCallback 란?

by 전지적진영시점 2023. 3. 5.
반응형

개발 환경

---------------------------------

OS : Mac

개발 툴 : android studio

개발 언어 : dart

---------------------------------

 

addPostFrameCallback의 존재를 알게된건

global 파일에다가 공통으로 쓰일 dialog를 선언해두었는데

테스트 삼아 initState()에서 호출했다가 아래와 같은 에러를 만나서 알게되었다.

 

E/flutter (11727): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: dependOnInheritedWidgetOfExactType<_LocalizationsScope>() or dependOnInheritedElement() was called before _MyHomePageState.initState() completed.
E/flutter (11727): When an inherited widget changes, for example if the value of Theme.of() changes, its dependent widgets are rebuilt. If the dependent widget's reference to the inherited widget is in a constructor or an initState() method, then the rebuilt dependent widget will not reflect the changes in the inherited widget.
E/flutter (11727): Typically references to inherited widgets should occur in widget build() methods. Alternatively, initialization based on inherited widgets can be placed in the didChangeDependencies method, which is called after initState and whenever the dependencies change thereafter.

 

_MyHomePageState.initState()가 완료되기 전에 dependOnInheritedWidgetOfExactType(), dependOnInheritedElement() 이 둘중에 하나가 호출되어서 발생한 에러다. 

 

그렇다면 initState() 의 역할은 무엇이냐

위젯이 생성될 때 처음으로 호출되는 메서드인데 이거 완료되고 나서 다음 작업 하라는 것 같다.

 

나의 해결 방법은 아래와 같다.

지금 실행하고 있는거 끝나고 callback 함수로 작업을 하겠다는거다 !

 

class _MyHomePageState extends State<MyHomePage> {
  @override
  void initState() {
    super.initState();

    WidgetsBinding.instance.addPostFrameCallback((_) async {
      common.dialog(context);
    });
  }

 

이상입니당

 

 

반응형

댓글