What are StatefulWidget and State Separate Classes?
What are StatefulWidget and State Separate Classes?
In Flutter, a StatefulWidget is defined using two separate classes: the StatefulWidget class itself and a corresponding State class. This design decision has several key reasons:
Widgets are immutable, so the StatefulWidget must also be immutable. However, the state of the widget needs to be mutable in order to change over time. By separating the widget and state into two classes, the immutability of the widget can be preserved while allowing the state to be mutable.
If the StatefulWidget and State were combined into a single class, creating a new instance of the widget (e.g. when its parent is updated) would reset the state every time. By separating them, the framework can create multiple instances of the StatefulWidget while preserving the same State instance.
Đăng nhập để tham gia thảo luận cùng mọi người.
Chưa có bình luận nào
Hãy là người đầu tiên chia sẻ suy nghĩ của bạn.