Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize variable inside 'initState' or just below the class definition? [duplicate]

Tags:

flutter

dart

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?

First method:

class _SampleState extends State<Sample> {
  String _foo = 'FOO';

  @override
  void initState() {
    // Do some other stuff
    super.initState();
  }

  ...
}

Second method:

class _SampleState extends State<Sample> {
  String _foo;

  @override
  void initState() {
    _foo = 'FOO';
    // Do some other stuff
    super.initState();
  }

  ...
}
like image 671
Eranga Heshan Avatar asked Jun 12 '20 09:06

Eranga Heshan


People also ask

When should I call 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.

What is super initState () in flutter?

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.


1 Answers

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?

like image 148
Sagar Acharya Avatar answered Sep 25 '22 19:09

Sagar Acharya