I am wondering when I know the initial value to a variable in a State
class in Flutter, whether I should initialize it with the variable definition or inside initState
method. What is better and why?
class _SampleState extends State<Sample> {
String _foo = 'FOO';
@override
void initState() {
// Do some other stuff
super.initState();
}
...
}
class _SampleState extends State<Sample> {
String _foo;
@override
void initState() {
_foo = 'FOO';
// Do some other stuff
super.initState();
}
...
}
super. initState() should always be the first line in your initState method. From docs: initState(): If you override this, make sure your method starts with a call to super.
It is a method called the first time a stateful widget is inserted in the widget-tree. – Rémi Rousselet. Sep 12, 2018 at 13:05. super. initState() forwards to the default implementation of the State<T> base class of your widget.
What I think is you can initially define it without using the initstate(), but if you assigning any value to it then there comes the initstate where you process some things like api calls or any other and then assign the value to it. For More details check out this link where Remi has explained :
is there any difference between assigning value to the variable inside of initState or not in Flutter StatefulWidget?
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