4

I'm migrating to null safety and have some setters that executes code if a value changes

set someValue(int value) {
    if ( _someValue != val ) {
        _someValue = val;
        // do some stuff
    }
}

Some of my variables now have late initialization due to migration and I'm understandably getting a LateInitializationError above when I check its value. Is there a way to check if a variable is initialized? E.g.,

set someValue(int value) {
    if ( !_someValue.isInitilized() || _someValue != val ) {
        _someValue = val;
        // do some stuff
    }
}
buttonsrtoys
  • 2,359
  • 3
  • 32
  • 52

1 Answers1

4

Short answer is you can't check that.

late is when you are sure that the variable will definitely be initialized, and not used before doing so. If you aren't sure that it will always not be null, then you should make it nullable

So instead of

late int _someValue;

Make it

int? _someValue;

set someValue(int value) {
    if ( !_someValue !=null || _someValue != val ) {
        _someValue = val;
        // do some stuff
    }
}
Huthaifa Muayyad
  • 11,321
  • 3
  • 17
  • 49