12

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();
  }

  ...
}
Eranga Heshan
  • 5,133
  • 4
  • 25
  • 48

3 Answers3

5

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?

Sagar Acharya
  • 3,397
  • 4
  • 12
  • 34
1

When you know the value at construction time, then i would suggest, you set it at construction time (in the constructor or as default value at the definition).

When you know the value at a specific time of the widget lifecycle, like at init, then use the respective method.

scrimau
  • 1,325
  • 1
  • 14
  • 27
1

The main difference is that initState() is called at the point when widget is already added to the tree and you already have access to this.context and this.widget.

So, unless you're using BuildContext or your instance of StatefulWidget, I recommend you to proceed with String _foo = 'FOO'; in the class declaration just because it looks simpler.

Third possible option is to assign _foo in the class constructor. Again, it makes sense only if the value of the property for some reason can't be assigned along with its definition, for example if it depends on values of other class properties.

Andrey Ozornin
  • 1,129
  • 1
  • 9
  • 24