I want to know the meaning of ?. operator in dart , if any one can explain it ? , thank you . for example : final length=names?.length;
CodePudding user response:
That means that you are accessing a property that may be null. When you declare a variable but never set it, you do this:
String? testString; // the ? operator means that the variable can be null
This was added to prevent your program from crashing by null pointer exceptions.
I suggest you read Michael Horns comment which includes the documentation for null safety in Dart.
CodePudding user response:
? is a nullable operator, meaning the variable you are accessing may be null.
An example below shows how you can perform operation on nullable variable:
String? data;
final bool hasData = (data ?? '').isNotEmpty;
bool? isCalled;
final bool isItReallyCalled = isCalled == true;
This way, you do not need to check if the variable is null or use the ! operator, which may cause null pointer exceptions.
