šÆBasics of Null Safety ā Flutter & Dart
Null Safety is Flutterās Feature šthat released with Flutter 2.0. (That Null safety feature also in other programming languages) And the introduction of Null Safety marked a significant milestone for the Dart programming language. Also, it makes Flutter & Dart more Strict & Less Prone to Errors & Bugs šĀ . Letās Decode itĀ !!
Null Safetyš”ļø
Null Safety, in simple words, means a variable cannot contain a ānullā value unless you initialize with null to that variable. With null safety, all the runtime null-dereference errors will now be shown in compile time.
Why Null Safety?
Null safety prevents errors that result from unintentional access of variables set to null
. For example, if a method expects an integer but receives null
, your app causes a runtime error. This type of error, a null dereference error, can be difficult to debug.
Null Safety Principleš®
- Non-nullable By Default: By default, Dart variables arenāt nullable unless you explicitly specify that they can be null. This is because non-null was by far the most common option in API research.
- Incrementally Adoptable: Migration to null safety is completely up to you. You can choose what to migrate to null safety, and when. You can migrate incrementally, combining null-safe and non-null-safe code within the same project.
- Fully Sound: As a result of Dartās sound null safety, compiler optimizations are possible. If the type system determines that something isnāt null, then it cannot be null. Null safety leads to fewer bugs, smaller binaries, and faster execution once your entire project and its dependencies are migrated to null safety.
Non-Nullable Types
When we use null safety, all the types are non-nullable by default. For example, when we declare a variable of type int, the variable will contain some integer value.
void main() {
int marks;
// The value of type `null` cannot be
// assigned to a variable of type 'int'
marks = null;
}Nullable Types
To specify if the variable can be null, then you can use the nullable type
operator, Lets see an example:
String? carName; // initialized to null by default
int? marks = 36; // initialized to non-null
marks = null; // can be re-assigned to null
Note: You donāt need to initialize a nullable variable before using it. It is initialized to null by default.
The Assertion Operator (!)
Use the null assertion operator ( ! ) to make Dart treat a nullable expression as non-nullable if youāre certain it isnāt null.
Example:
int? someValue = 30;
int data = someValue!; // This is valid as value is non-nullable
In the above example, we are telling Dart that the variable
is null, and it is safe to assign it to a non-nullable variable i.e.
Type Promotion
Dartās analyzer, which tells you what compile-time errors and warnings, is intelligent enough to determine whether a nullable variable is guaranteed to have values that are not null. Dart uses Flow Analysis at runtime for type promotion (flow analysis is a mechanism that determines the control flow of a program).
Example:
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));
} // This is valid as value is non-nullable
In the above code, if statement checks if the value is null or not. After the if statement value cannot be null and is treated ( promoted) as a non-nullable value. This allows us to safely use
instead of
(with the null-aware operator). Here
function will return an absolute value.
Late Keyword
As we knew that all variables are non-null by default, we can use either the ? operator or the late keyword.
Example:
String? carName; // using ? operator
late String bikeName; // using "late" keyword
Enabling null safety.
You can use sound null safety in Dart 2.12 and Flutter 2.0 or later. Dart 3 and later will only support sound null safety.
To enable sound null safety, set the SDK constraint lower-bound to a language version of 2.12 or later. For example, your pubspec.yaml
file might have the following constraints:
environment:
sdk: '>=2.12.0 <3.0.0'
Null Safety Benefits
- This feature improves user satisfaction by reducing errors and app crashes.
- We can write null-safe code with strong compile-time guarantees. This makes us productive because Dart can tell us when weāre doing something wrong.
- We can more easily declare our intent. This leads to APIs that are self-documenting and easier to use.
- The Dart compiler can optimise our code, resulting in smaller and faster programs.
Learn more
- You can read the official article on null safety.
- Furthermore as mentioned at the beginning, you can play with it on DartPad.
Conclusion
As far as type safety is concerned, Dart is unbeatable. Null safety helps you avoid numerous errors in your program. And we can improve quality of Flutter applications and give great user experience from the application.
Happy coding!