Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we need stateless widgets if the same can be achieved by stateful widgets in flutter?

I am a newbie in the world of flutter, and I recently learned (or I think I did) about stateful and stateless widgets which is kind of the base for flutter widgets.

We use stateless widgets for things that are not redrawn on the display, (like text, button etc.) but stateful widgets can redraw themselves.

So my question is why do we need stateless widgets if stateful widgets can be used to draw the same kind of widgets that a stateless widget can?

Or is there any specific reasons to use stateless over stateful widgets in flutter? Or can we use stateful widgets all the time rather than stateless widgets which can draw content only once?

Thanks, and sorry if this is a stupid question.

EDIT

Well the question is not the difference between stateless and stateful. I know the difference but what is the impact of using only stateful widgets since by using it we could also implement most of the things a stateless widget can do then why do we need stateless widgets?what's the importance of it in a flutter environment were most of the apps will be re-drawn time-to-time?

like image 789
Jithin Avatar asked Sep 05 '19 05:09

Jithin


1 Answers

Yes, StatefulWidget can rebuild. That happens typically when using Inheritedwidgets.

StatelessWidget exists to split a big widget tree into smaller reusable widgets.

You might think "but I can use StatefulWidget or functions for this". Which is true, but not exactly:

  • StatefulWidget comes with a huge boilerplate, which you do not need in that situation. So this just adds noise and makes your code less readable.
  • Functions cannot rebuild independently, nor to they have access to key and override ==. So they can be less performant or introduce bugs.
like image 173
Rémi Rousselet Avatar answered Sep 29 '22 05:09

Rémi Rousselet