flutterdartvariablesinitialization

How to check 'late' variable is initialized in Dart


In kotlin we can check if the 'late' type variables are initialized like below

lateinit var file: File    
if (this::file.isInitialized) { ... }

Is it possible to do something similar to this in Dart..?


Solution

  • Unfortunately this is not possible.

    From the docs:

    AVOID late variables if you need to check whether they are initialized.

    Dart offers no way to tell if a late variable has been initialized or assigned to. If you access it, it either immediately runs the initializer (if it has one) or throws an exception. Sometimes you have some state that’s lazily initialized where late might be a good fit, but you also need to be able to tell if the initialization has happened yet.

    Although you could detect initialization by storing the state in a late variable and having a separate boolean field that tracks whether the variable has been set, that’s redundant because Dart internally maintains the initialized status of the late variable. Instead, it’s usually clearer to make the variable non-late and nullable. Then you can see if the variable has been initialized by checking for null.

    Of course, if null is a valid initialized value for the variable, then it probably does make sense to have a separate boolean field.

    https://dart.dev/guides/language/effective-dart/usage#avoid-late-variables-if-you-need-to-check-whether-they-are-initialized