How to Check if a Variable is Null in Flutter and Dart

Updated: February 5, 2023 By: A Goodman Post a comment

This quick article shows you a couple of different ways to check whether a variable is Null or not in Flutter (and Dart as well).

Using the equality operator (“==”)

In Flutter (and Dart), you can check if a variable is Null or not by using the equality operator (the double equal sign), like this:

if (a == null){
  //
} else {
  //
}

Here’s a working, reproducible example:

// a dummy function that returns an integer or null
int? doSomething(bool returnNull) {
  if (returnNull) {
    return null;
  }

  return 1;
}

void main() {
  var x = doSomething(true);
  var y = doSomething(false);

  if (x == null) {
    print('x is null');
  } else {
    print('x is not null');
  }

  if (y == null) {
    print('y is null');
  } else {
    print('y is not null');
  }
}

Output:

x is null
y is not null

Using the “??” operator

The ?? operator returns the value on the right side of the operator if the value on the left side is null. Let’s examine the following example for more clarity:

// a dummy function that returns an integer or null
int? doSomething(bool returnNull) {
  if (returnNull) {
    return null;
  }

  return 1;
}

void main() {
  var x = doSomething(true);
  var y = doSomething(false);

  var z = x ?? 'Because x is null, this text is assigned to z';
  print(z);

  print(y ?? 'Because y is null, this text is printed');
}

Output:

Because x is null, this text is assigned to z
1

Using the “?.” operator

The “?.” operator is used to safely access a property or a method of an object. If the object is null, the operator will return null instead of throwing an error.

Example:

// kindacode.com
void main() {
  var variable;
  var value = variable?.toString();
  print(value);
}

Output:

null

Conclusion

When working with Flutter, especially when fetching and processing data, you will often have to check if your variables are Null or not. This helps your application avoid crashing in the future.

Flutter is an amazing tool for producing mobile and web apps. Continue learning more interesting things by taking a look at the following articles:

You can also tour around our Flutter topic page or Dart topic page for the most recent tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles