Search code examples
flutterwidgetstatelessstateful

Flutter: When to create Stateless or Stateful page?


I am new to Flutter. Everything in Flutter is a widget, and there are two types of widgets, which are Stateless and Stateful. Understood that stateless widgets are widgets that will not change or user can't interact with (texts, icons, etc) while stateful widgets are widgets that will change its state for example because of user interactions.

When we want to create a new custom page we usually extends the page from StatelesWidget or StatefulWidget. Since a StatelesWidget can have StatefulWidget as its children and vice-versa, then when should we extend a page as a StatefulWidget or as a StatelessWidget?

Thank you.


Solution

  • If the page itself has some kind of status, then it should be a stateful widget. For example you want to load something remotely, and display a progress indicator while data is being fetched. When loading is complete, the state of the page is changed, and instead of the progress indicator you display whatever you want.

    But it is also possible that the page itself is a stateless widget, and has a child widget, a container for example, and this container is stateful, managing the above mentioned remote loading or depends on some kind of user interaction.

    State management is a central issue in Flutter, you have many options, and it is not always easy to find the best. You can easily get into fighting the framework instead of letting it to do the job for you. If you are new to this, I would suggest watching some videos, they helped me a lot, for example this or this.