Dart Null Safety Code Example

Introduction To Null Safety In Dart

What is Dart Null Safety?

In basic terms, null safety in dart means that a variable cannot have a ‘null’ value unless it was started with null. All runtime null-dereference problems will now be shown at compile time, thanks to null safety.

String name = null ; // This means the variable name has a null value.Code language: JavaScript (javascript)

Dart Null Safety Code Example

class Car {
String carName = "Aston Martin";
}
 
void main() {
  Car cars;
  print(cars.carName);
}Code language: JavaScript (javascript)

We constructed a class in the preceding dart code and initialized a variable named carName within it. We declared a variable kind of automobile, cars, in the main() method. However, when we run the above code, we get an error.

Output:

Error: Non-nullable variable 'cars' must be assigned before it can be used.Code language: JavaScript (javascript)

The object was not initialized in the code above. To resolve this issue, we must:

class Car {
String carName = "BMW";
}

void main() {
Car cars = new Car();
print(cars.carName);
}Code language: JavaScript (javascript)

Output:

BMW

It is straightforward to detect which variable is not initialized in the given code, but identifying such problems in a large codebase may be complex and time-consuming. Null safety solves this problem.

  • Dart variables aren’t nullable by default unless you expressly state that they can be null. This is because in API research, non-null was by far the most popular choice.
  • It is entirely up to you to make the switch to null safety. You may decide when and what to move to null safety. Within the same project, you can migrate in stages, integrating null-safe and non-null-safe code.
  • Compiler optimizations are feasible because to Dart’s sound null safety. Something cannot be null if the type system concludes that it isn’t null. Once your whole project and its dependencies have been moved to null safety, you’ll notice fewer defects, smaller binaries, and quicker execution.

Non-Nullable Types

When we employ null safety, all types are by default non-nullable. When we declare a variable of type int, for example, the variable will hold an integer value.

void main() {
int marks;

// The value of type `null` cannot be
// assigned to a variable of type 'int'
marks = null;
}Code language: JavaScript (javascript)

Output:

Non-nullable variables must always be initialized with non-null values.Code language: JavaScript (javascript)

Nullable Types

You can use the nullable type to declare if a variable can be null. Let’s have a look at an example:

String? carName;  // initialized to null by default
int? marks = 36;  // initialized to non-null
marks = null; // can be re-assigned to nullCode language: JavaScript (javascript)

A nullable variable does not need to be initialized before being used. It comes with a null value by default.

The Assertion Operator (!)

If you’re convinced a nullable expression isn’t null, use the null assertion operator (!) to have Dart regard it as non-nullable.

int? someValue = 30;
int data = someValue!; // This is valid as value is non-nullableCode language: JavaScript (javascript)

We’re informing Dart that the variable someValue is null, and that it’s okay to assign it to a non-nullable variable, such as data, in the preceding example.

Type Promotion

Dart’s analyzer, which shows you what compile-time faults and warnings you have, can inform you if a nullable variable is guaranteed to contain non-null values. Dart promotes types via Flow Analysis at runtime (flow analysis is a mechanism that determines the control flow of a program).

int checkValue(int? someValue) {
if (someValue == null) {
	return 0;
}
// At this point the value is not null.
return someValue.abs();
}

void main(){
print(checkValue(5));
print(checkValue(null));
}Code language: PHP (php)

The if statement in the above code determines if the value is null or not. The value cannot be null after the if statement and is considered (promoted) as a non-nullable value. This allows us to utilize someValue.abs() instead of someValue?.abs() with confidence (with the null-aware operator). .abs() method will return an absolute value in this case.

Late” Keyword In Dart Null Safety

We may use either the? operator or the late keyword since all variables are non-null by default.

String? carName;	 // using ? operator
late String bikeName; // using "late" keywordCode language: JavaScript (javascript)

Advantages of Using Null Safety

It provides a better development environment with fewer runtime errors.
Dart Compiler can optimize our code, which will led to smaller and faster programs.Code language: JavaScript (javascript)

Conclusion

In this article, we took a look at the fundamentals on null safety in Dart, and how to work with this concept when it comes to developing flutter applications that implement null safety using Dart in them. As always, If you have found this article useful do not forget to share it and leave a comment if you have any questions. Happy Coding 🙂


Posted

in

, , ,

by

Comments

Leave a Reply