DEV Community

Iqra Fatima
Iqra Fatima

Posted on

Flutter: Difference Between Stateful and Stateless Widget

📲 As we know that all the User Interface(UI) components in Flutter are known as widgets. The widgets can be just of two types.

  • 1️⃣ Stateful Widgets 
  • 2️⃣ Stateless Widget

Let's discuss how they differ:

Stateless Widget

A stateless widget can not change their state during the runtime of an app which means it can not redraw its self while the app is running. Stateless widgets are immutable.

🤔 How to create a Stateless Widget ?!

🤔 How to create a Stateless Widget ?!
Alt Text

Let's understand this code snippet.
The name of the stateless widget is HomeScreen, inside which we have to override the build method. The build method takes the BuildContext as parameters and returns a widget. Below there is the place where you can design the UI of the HomeScreen.

The build(…) function of the StateLessWidget is called only ONCE. To redraw the StatelessWidget, we need to create a new instance of the Widget.

😕 Where to use?!

A stateless widget is used where you are not required to redraw a widget again & again, such as AppBar, scaffold, & icons, etc.

Stateful Widget

A stateful widget can redraw itself multiple times, while the app is running which means its state is mutable. For example, when a button is pressed, the state of the widget is changed.

🤔How to Create a Stateful Widget?!

Look at the structure of the stateful widget:
Alt Text
Let's understand this code snippet.
Here we have a class of HomeScreen which extends from a Statefulwidget & it has to return the instance of the class _HomeScreen in the createState() method. The class _HomeScreenState extends from State<> which takes HomeScreen as a template input.

Now, this _HomeScreenState overrides the build method and returns a widget. Below there you can add the UI of the app, which is stateful and can be called multiple times using setState method.

😕 Where to use?!

Let's say you have a timer on the top of your app & the state of it is changing every second. If your entire app is in a stateful widget then its rebuilding the entire app every second which is pretty expensive. If you just extend the TimeText to a stateful TimerText then an only tiny piece of app is updating every second now.

👋 That’s all folks, thanks! if you like this post, don’t forget to leave a comment! 🤩

Oldest comments (2)

Collapse
 
danielgomezrico profile image
Daniel Gomez

Thanks for this, one thing that confuse me is that if you call setState from the StatelessWidget the build function is called like a StatefullWidget, can you explain me why? and why we should not use StatelessWidget when we need to update the state of the widget after some actions?

Collapse
 
mpembainc profile image
Hussein Muhammad

It's amazing, you can explain at least one example of how setState() work?