Home > OS >  What is the difference between using `late` keyword before the variable type or using `?` mark after
What is the difference between using `late` keyword before the variable type or using `?` mark after

Time:09-29

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?

CodePudding user response:

when you use late keyword you can't let variable uninitialized when you called it with ? allows to you let variable uninitialized when you create it and call it

CodePudding user response:

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.

  • Related