본문 바로가기

✏️/Flutter

[flutter] widget에 대해서 알아보자! (immutable, life-cycle)

728x90

오늘은 flutter의 UI를 구성하는 요소인, widget에 대해서 알아봅시다.

위젯은, 상태가 변경되면 다시 빌드 합니다. 다시 말해 widget에 대해서 life-cycle로 관리를 하는 것이 아닌, 변경 점이 생기면 그 위젯을 다시 re-build 하여 그려준다는 것!

공식 문서의 widget class에서는 이렇게 이야기 하네요!

Widgets themselves have no mutable state (all their fields must be final). If you wish to associate mutable state with a widget, consider using a StatefulWidget, which creates a State object (via StatefulWidget.createState) whenever it is inflated into an element and incorporated into the tree.


해석해보면, 모든 widget은 immutable(변경 불가능한) 하며, mutable하게 사용하고 싶으면 stateful widget의 state object를 사용해라~ 정도가 되겠네요!

흠 .. 그럼 위젯은 immutable한 거네!,,
그럼 우리가 흔히 알고 있는 widget life cycle(생명주기)은 뭐야?! 가변적이지 않다면 생명주기도 없는 것 아니야???!

좋은 질문 입니다..! 모든 위젯은 immutable하기 때문에 life-cycle을 바로 연상 하실 수 있을 텐데요,하지만 우리는 이 질문에 대한 답을 이미 잘 알고 있습니다!!
Stateful Widget을 만들 때 자세히 보면, State 객체를 만듭니다.

class myStatefulWidget extends StatefulWidget {
  @override
  _myStatefulWidgetState createState() => _myStatefulWidgetState();
}

class _myStatefulWidgetState extends State<myStatefulWidget> {
  // ···
}

여기서 우리가 암묵적으로 생성하는 State 객체는 위젯에게 다음과 같은 역할을 수행 할 수 있도록 해줍니다.
1) 위젯이 빌드 될 때 동적으로 값을 읽는 역할 (can be read synchronously when the widget is built.)
2) 위젯이 life-cycle에 맞게 변경 가능하도록 하는 역할 (change during the lifetime of the widget.)

따라서, State class를 extend 함에 따라서 Widget이 마치 immutable하게 사용 할 수 있게 된 것이죠!!
> 그래서 애니메이션 효과를 보여줄 떄는 위젯들을 만들고 폐기하는 과정을 빠르게 보여줘서 표현한다네요~~

그렇다면, widget의 생명주기는 State에 따라 어떻게 작동되는지 한번 살펴볼까요?

1. createState 호출 하여 State 객체 생성
2. State 객체와 buildContext에 mount 됨
3. 위젯이 생성되면서  initState 호출 : 생성된 widget buildcontext 초기화 
4.  didChangeDependencies 호출 : inheritedWidget 초기화
5. build 호출 : setState가 호출되면 하위 트리를 다시 빌드하도록 요청
6. didUpdateWidget : 현재 위젯을 다음 위젯에게 넘겨줄 때 
** 핫 리로드 :  reassemble 메소드가 호출되며, initState 메소드부터 시작
7.  deactivate : State를 가지고 있는 하위 트리가 메인 트리에서 제거 될 때 호출
8. dispose : State 객체가 다시 빌드 되지 않음을 나타냄 
9. 마운트 해제 (mounted false) : 생명주기의 회종 단계 (State 객체 폐기)

조금은 어렵지만, 공식 문서에 있는 내용들을 정리한 것이니! 자세히 알고 싶으면 아래 링크를 통해 확인해 주시면 될 것 같습니다 ㅎㅎ

 

--
참고

https://flutter.dev/docs/development/ui/widgets-intro

 

Introduction to widgets

Learn about Flutter's widgets.

flutter.dev

https://api.flutter.dev/flutter/widgets/Widget-class.html

 

Widget class - widgets library - Dart API

Describes the configuration for an Element. Widgets are the central class hierarchy in the Flutter framework. A widget is an immutable description of part of a user interface. Widgets can be inflated into elements, which manage the underlying render tree.

api.flutter.dev

https://api.flutter.dev/flutter/widgets/State-class.html

 

State class - widgets library - Dart API

State class Null safety The logic and internal state for a StatefulWidget. State is information that (1) can be read synchronously when the widget is built and (2) might change during the lifetime of the widget. It is the responsibility of the widget imple

api.flutter.dev