Why do we need to initialize late a class on run time and not directly on compile time in flutter?

Viewed 35

I'm wondering, if we create an instance of a class, we create the instance first and mark it as late before assigning a value on the initState? Why dont we just assign a value to it at compile time directly?

//what is the difference of this
SampleClass _sample = SampleClass();

//with this?
late SampleClass _sample;

void initState(){
  super.initState():
  _sample = SampleClass();
}
1 Answers

When SampleClass depends on context, the initialization must happen in initState which is when the widget is inserted into the tree, otherwise no need to delay the initialization.

Related