dart

Assign a value to a variable if it is null using Dart

We can use null check operators in dart to assign a value to a variable. Here we are using ??= to check null values.

void main() {
  int? a; // a is null here
  a ??= 10; // will assign 10 to a as its null
  print(a); // -> Prints 10.

  a ??= 50; // will not assign 50
  print(a); // <-- Still Prints 10.

  var name = null ?? 'Ankit'; //Will assign Ankit as first value is null
  print(name);
}

Printing a value if it is null

void main() {
   String name = "John" ?? "Rick";
   print(name);
}

Output

John

In the above program if the first value is not null then it will be assigned to the variable and if it is null then the second value will be assigned to it. Lets understand it with the below example.

void main() {
   String name = null ?? "Rick";
   print(name);
}

Output

Rick

Here the first value is null so it will not be assigned to name variable.

The basic syntax for that is 

"first value" ?? "second value"

The value which is not null will be assigned to the variable.

Was this helpful?