Stateful Widget의 life cycle

[Flutter] Widget의 Life cycle

1. initState

플러터나 위젯의 라이프 사이클을 몰라도 익숙한 함수이다.
해당 위젯이 로드 될때 필요한 초기화를 진행하게 된다.
빌드 이전에 한번만 실행되며 안드로이드 스튜디오의 onCreate
유니티의 Awake 함수에 해당한다.

2. didChangeDependencies

initState직후에 호출된다.
또한 InheritedWidget으로부터 종속된 경우 그 위젯이 변경될때 다시 호출된다.

3. build

라이프 사이클을 통틀어 가장 중요한 부분으로 여기에서 위젯을 렌더링한다.
didChangeDependencies 이후 호출되며 다시 그리는 비용이 저렴하다.
UI를 렌더링 할때마다 호출된다.

4. didUpdateWidget

자주 접하게 될 라이프 사이클은 아니지만 상위 위젯이 변경되고
UI를 다시 그려야 할 때 호출된다.
파라미터로 oldWidget을 가져오고 현재 위젯과 비교하여 추가논리를 수행 할 수 있다.

5. dispose

initState와 반대의 라이프 사이클로 해당 개체가
위젯트리에서 영구적으로 제거되고 다시 빌드되지 않을 때 호출된다.
여기선 스트림을 구독 취소하거나 애니메이션을 삭제하는 등의 일을 하게된다.

build 이후에 한번만 실행

가령 처음에 위젯을 하나 생성후에 애니메이션을 재생시키고 싶다면
위의 라이프 사이클로는 수행 하기 어렵다.
하지만 방법이 있으니 바로 initState함수에 addPostFrameCallback함수를 호출 하는것이다.

1
2
3
4
5
  void initState() {
    super.initState();
    WidgetsBinding.instance
        .addPostFrameCallback((_) => yourFunction(context));
  }
cs

참고

라이프 사이클 : https://medium.com/flutter-community/flutter-lifecycle-for-android-and-ios-developers-8f532307e0c7

 

Flutter Lifecycle for Android and iOS Developers

One of the most confusing ideas transitioning from Android and/or iOS is to understand how Flutter handles its lifecycle.

medium.com

addPostFrameCallback : https://stackoverflow.com/questions/49466556/flutter-run-method-on-widget-build-complete

 

Flutter: Run method on Widget build complete

I would like to be able to run functions once a Widget has finished building/loading but I am unsure how. My current use case is to check if a user is authenticated and if not, redirect to a login...

stackoverflow.com

 

+ Recent posts