Why are stateful widgets defined as two classes in flutter?

There are multiple reasons :

  • Widgets are immutable. Since StatefulWidget extends Widget it therefore must be immutable too. Splitting the declaration into two classes allows both StatefulWidget to be immutable and State to be mutable.

  • Widgets are instantiated using the syntax new MyWidget(). If we merged both classes into one, 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 to it’s Stateful part using the this.widget field.
The generic is here to make that field of type MyStateful instead of just StatefulWidget. As you may want to access MyStateful properties.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)