Is there a way to check if late variable has been initialized

586

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
    }
}
Share:
586
buttonsrtoys
Author by

buttonsrtoys

Updated on December 29, 2022

Comments

  • buttonsrtoys
    buttonsrtoys over 1 year

    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
        }
    }
    
  • Francisca Mkina
    Francisca Mkina over 2 years
    A negation operand must have a static type of 'bool'.