Search code examples
flutternullnon-nullable

What is the difference between using `late` keyword before the variable type or using `?` mark after the variable type it in the Flutter?


I think in new Dart rules the variables can not be declared/initialized as null. So we must put a late keyword before the variable type like below:

late String id;

Or a ? mark after the variable type like below:

String? id;

Are these two equal Or there are some differences?


Solution

  • A nullable variable does not need to be initialized before it can be used.

    It is initialized as null by default:

    void main() {
      String? word;
      
      print(word); // prints null
    }
    

    The keyword late can be used to mark variables that will be initialized later, i.e. not when they are declared but when they are accessed. This also means that we can have non-nullable instance fields that are initialized later:

    class ExampleState extends State {
      late final String word; // non-nullable
    
      @override
      void initState() {
        super.initState();
    
        // print(word) here would throw a runtime error
        word = 'Hello';
      }
    }
    

    Accessing a word before it is initialized will throw a runtime error.