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

Viewed 3335

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

  ...
}
3 Answers

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.

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.

Related