Why Stateful Widgets Defined as two Classes In Flutter ??

· 3 min read
Why Stateful Widgets Defined as two Classes In Flutter
Why Stateful Widgets Defined as two Classes In Flutter

A Stateful Widget will maintain data and will react accordingly to whatever the data is doing within the mobile application. A Stateful Widget with parameters is a mutable widget that is the reason it can be drawn multiple times within its lifetime. so in this article, we will walk through why Stateful Widgets Defined as two classes in flutter ??

Why Stateful Widgets Defined as two Classes In Flutter ??

There are multiple reasons :

  • Widgets are immutable. Since the Stateful widget extends Widget it, therefore, must be immutable too.
  • Splitting the declaration into two classes allows both the Stateful widget API to be immutable and State to be mutable.
  • Widgets are instantiated using the syntax new MyWidget(). If we merged both classes into one, the new MyWidget() would reset all the properties of the state every time its parent update.

As for the explanation of class _MyStatefulState extends State<MyStateful>

That is because the State class can access its Stateful part using the this.widget field. The generic is here to make that field of type MyStateful instead of just Stateful Widget. As you may want to access MyStateful properties.

class YellowBird extends StatefulWidget

A stateful widget is an immutable class that means that once an object is created, we cannot change its values.

1- The class must be declared as final so that child classes can’t be created

2- Data members in the class must be declared as final so that we can’t change the value of it after object creation

3- A parameterized constructor

4- Getter method for all the variables in it. No setters to not have the option to change the value of the instance variable

class _YellowBirdState extends State

State class which type is generic is a mutable class that can be instantiated with different values after creating its object.

same as this stateful widget class which is immutable is calling a function of createState() which define the class State of the widget after it called in a flutter.

So we can change the values of the widget again and again by this approach but we cannot change the type of Stateful or Stateless.

Conclusion:

Hope you enjoyed this article !!!

In this article, we have been through why stateful widgets defined as two classes in the flutter and also its lifecycle.

Do not forget to drop your valuable suggestions/feedback. We would love to assist you.

FlutterAgency.com is our portal Platform dedicated to Flutter Technology and Flutter Developers. The portal is full of cool resources from Flutter like Flutter Widget GuideFlutter ProjectsCode libs and etc.

FlutterAgency.com is one of the most popular online portals dedicated to Flutter Technology and daily thousands of unique visitors come to this portal to enhance their knowledge of Flutter.

Leave a Reply