I'm new to flutter/dart, so while I try to make an app I also try to understand why things are a certain way. In the flutter docs there is example code of a stateful widget as shown:
class YellowBird extends StatefulWidget { const YellowBird({ Key key }) : super(key: key); @override _YellowBirdState createState() => new _YellowBirdState(); } class _YellowBirdState extends State<YellowBird> { @override Widget build(BuildContext context) { return new Container(color: const Color(0xFFFFE306)); } }
Questions:
Why are they defined with two classes as opposed to one? I'm guessing the State class can be used somewhere else so it was better to be split up.
From what I understand the createState()
function returns an object of type State
, so having _YellowBirdState extends State
makes sense, but why is YellowBird
passed into the generic class of State
? My guess it has something to do with Yellowbird
extending the StatefulWidget
class but not quite sure.
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.
A widget is either stateful or stateless. If a widget can change—when a user interacts with it, for example—it's stateful. A stateless widget never changes. Icon , IconButton , and Text are examples of stateless widgets.
Stateful Widgets are dynamic widgets. They can be updated during runtime based on user action or data change. Stateful Widgets have an internal state and can re-render if the input data changes or if Widget's state changes. For Example: Checkbox, Radio Button, Slider are Stateful Widgets.
A stateful widget can change its appearance in response to user interaction or when it receives data e.g. Checkbox, Radio, Slider, TextField, etc. We can, for example, move the Slider thumb and change its value. This change in value changes its appearance. These widgets subclass the StatefulWidget class.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With