Dart Tutorials

Null Safety in Dart and Flutter

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
*/

}

Related Posts

working with list in Dart/Flutter

Working with List in Dart/Flutter

A list is a way of storing data in a list of order. In other programming, languages like PHP and javascript Array is used as a list. List…

working with list in Dart/Flutter

Dart Override toString() method In a class

If you have a class and you override the toString() method, it will return such a string method when the instance/object of the class is printed. Why? when…

working with list in Dart/Flutter

Working with DateTimes in Dart Or Flutter with examples

The DateTime class provides methods to work with dates and times when developing flutter or dart applications. An example could be an instance in time of June 20,…