State란?
우리는 flutter를 개발하면서 State란 말을 많이 접하게 된다.
한국말로 번역하면 상태지만, flutter에서도 동일한 의미로 쓰일까?
State
Flutter에서 state는 데이터를 의미한다.
UI를 통해 사용자에게 보여주는 데이터, APP을 통해 사용자와 상호작용하며 변화하는 데이터, 내부적으로 사용되는 데이터등이 이에 속한다.
그러면 StatelessWidget과 StatefulWidget은 각각 데이터가 없는 위젯과 데이터가 넘쳐나는 위젯을 의미하는 걸까?
Flutter 공식 홈페이지에서
StatelessWidget - A widget that does not require mutable state.
(api.flutter.dev/flutter/widgets/StatefulWidget-class.htmlapi.flutter.dev/flutter/widgets/StatelessWidget-class.html)
StatefulWidget - A widget that has mutable state
(api.flutter.dev/flutter/widgets/StatefulWidget-class.html)
라고 설명한다.
해석해보면,
StatelessWidget은 변화가 가능한 State가 필요하지 않은 위젯,
StatefulWidget은 변화가 가능한 State를 갖는 위젯
이라고 해석된다.
즉, State를 데이터로 바꿔서 봐보면
StatelessWidget은 변화 가능한 데이터가 필요하지 않은 위젯,
StatefulWidge은 변화 가능한 데이터를 갖는 위젯을 의미한다.
다르게 해석해보면,
StatelessWidget은 불변의 데이터를 갖는 위젯,
StatefulWidget은 변화 가능한 데이터를 갖는 위젯을 의미한다는 것이다.
두 위젯의 생명주기를 보기전에 BuildContext에대해 먼저 알아보자.
BuildContext
Context는 flutter에서
A Context is a data structure which holds the captured variables for some closure. 라고 설명한다.
해석해도 잘 이해가 가지 않아 다른 글을 찾아봤다.
www.didierboelens.com/2018/06/widget-state-context-inheritedwidget/
Flutter - Widget - State - Context - InheritedWidget
Flutter - This article covers the important notions of Widget, State, Context and InheritedWidget in Flutter Applications. Special attention is paid on the InheritedWidget which is one of the most important and less documented widgets. Difficulty: Beginner
www.didierboelens.com
해당 글에서 context는 A context is nothing else but a reference to the location of a Widget within the tree structure of all the Widgets which are built. 라고 설명한다.
즉, Context는 트리 구조내에서의 위젯 위치에대한 참조이다.
다르게 말해 Context는 트리 구조내에서 위젯 위치에대한 연결 수단이다.(위젯의 트리 구조내에서 위젯 위치를 알려주는 애정도로 생각하자.)
그럼 BuildContext는 무엇일까?
BuildContext는 빌드된 위젯의 트리구조 내에서 위젯의 위치를 알려주는 참조를 위미한다.
즉, BuildContext는 빌드된 위젯의 트리구조 내에서 위젯의 위치를 알려주는 애라고 생각하면된다.

이제 StatelessWidget과 StatefulWidget의 생명주기를 알아보자.

StatelessWidget은 하나의 StatelessWidget이 많은 BuildContext를 만들 수 있고,
StatefulWidget은 각 BuildContext의 새로운 StateObject를 만들 수 있다고 한다.
StateObject의 생명주기

State object가 다시 build를 하는 경우는 configuration이 바뀌었거나, 또는 setState 호출로 인해 내부적으로 상태가 변화했을 때 다시 build하게 된다.
그래서 StateManagement는 왜 하는것인가?
State Object만을 이용해 State를 관리하게 되면, 앱이 아주 간단한 count up, down을 하는 앱이나 계산기같은 경우는 StateManagement가 필요하지 않다. 왜냐하면, StatefulWidget 하나에 다 만들면 되기 때문이다.
하지만 복잡한 widget tree 구조의 app들은 StateManagment가 필요하다. widget tree 구조상 동떨어진 widget끼리 통신을 필요로 할때 StateManagement가 그 역할을 해주기 때문이다.
참고 - medium.com/flutter-korea/flutter-state-management-%EC%8B%9C%EC%9E%91-a5408f7a86dd