Home > Software engineering >  Flutter, late keyword with declaration
Flutter, late keyword with declaration

Time:09-25

late TextEditingController _controller = TextEditingController();
late String someString = "someString";

TextEditingController _controller = TextEditingController();
String someString = "someString";

Are they still different? or exactly same??? on any circumstances (in performances)

CodePudding user response:

late modifier means “enforce this variable’s constraints at runtime instead of at compile time”. It’s almost like the word “late” describes when it enforces the variable’s guarantees.

Lazy initialization The late modifier has some other special powers too. It may seem paradoxical, but you can use late on a field that has an initializer:

class Weather {
  late int _temperature = _readThermometer();
}

When you do this, the initializer becomes lazy. Instead of running it as soon as the instance is constructed, it is deferred and run lazily the first time the field is accessed. In other words, it works exactly like an initializer on a top-level variable or static field. This can be handy when the initialization expression is costly and may not be needed.

Running the initializer lazily gives you an extra bonus when you use late on an instance field. Usually, instance field initializers cannot access this because you don’t have access to the new object until all field initializers have completed. But with a late field, that’s no longer true, so you can access this, call methods, or access fields on the instance.

More and ref understanding-null-safety

  • Related