Should screens be Stateless or Stateful?

Viewed 1465

I'm developing an app with lots of screens and pages. I've read somewhere that you should use Stateless Widgets whenever you can.

Why is that?

If I have a lot of screens, should those be stateless? And then the content inside be Stateful? Is it better to have both the screen and widgets inside being Stateful?

2 Answers

You should ask yourself some questions about the screen/page to decide if it will be Stateless or Stateful.

  • The most obvious, does it need to change state?
  • Do you need to call initState, didChangeDependencies or another lifecycle method?

Is a bad practice to make Stateful when not needed. A good idea might be to start always as Stateless widget and if needed you can change it to Stateful easily with Alt + Enter shortcut (Android Studio).

I always start by creating a Stateless Widget and work with it until I have to change something state. So I could quickly use `Alt-Enter/ Convert to a Statefull from Intellij/AS to change it to stateful. (doing the inverse is not so easy, so...).

Moreover, if you use Stateful widget with some async mechanism, like streams, you could build the widget once and use the streams to update the information you need, and it will not impact the performance of your app so much. But if you call setState many times, this can degrade your App, since for every setState the Widget tree will be rebuilt.

This article from the flutter docs shows interesting tips about handling state change in flutter apps:

Related