By default, all Dart variables and methods are non-nullable, meaning they can’t be or return null. So, to make a variable or method nullable, meaning to be or return null, you have to use the null-safety operator “?” on it datatype or before the variable or method.
You have to also use the symbol ! to check if a particular variable has a null value. If the value is null, Dart will throw an exception.
Example:
// Non-nullable ==> means it must have a value before using it (can't be null).
String myName;
print(myName); // this will be an error since is Non-nullable
// Nullable ==> means it can be null before using it
String? email;
print(email); // this print null, without causing any error
String school = null; // it will be error, you're assigning null value to a Variable that must not be null
String? church =null; // Correct no error, because it marked nullable to accept null values
String getName(){
return null; //error: the method is non-nulllable it must not return null
}
String? getTown(){
return null; // correct: the method is marked nullable
}
List<String> colors1 =[null]; // error
List<String> colors2 =null; //error
List<String?> newcolors =[null]; // correct
List<String>? colors =null; //correct
Check also, How to solve null check operator used on a null value?
Use the “!” to check if a variable has a null value
void main(List<String> args) {
// make the variable nullable but don't assign any value to it
String? firstName;
// use the "!" to check if the <firstName> has a value of null
// if the value is not null, dart will not throw an exception
//But if it has a value of null, dart will throw an exception like:
// Null check operator used on a null value
print(firstName!);
/* result:
Unhandled exception:
Null check operator used on a null value
*/
}