What is meant by null safety ? and how can we implement it in flutter?
Null safety is a feature in programming languages that helps prevent null reference errors by guaranteeing that an object cannot be null unless it is explicitly declared as such. This means that the programmer/Developer must explicitly declare which variables or objects can contain a null value and which cannot. This makes it easier to detect and prevent errors that occur when a null value is accessed or used, as the language will throw an error when an attempt is made to access a non-null variable that has been assigned a null value. Null safety helps make code safer and more robust, reducing the likelihood of bugs and unexpected behavior in applications.
In Flutter, null safety is a feature that was introduced in Dart 2.12 and helps prevent null reference errors by guaranteeing that an object cannot be null unless it is explicitly declared as such. To use null safety in Flutter, you need to use Dart 2.12 or later.
You can declare variables as non-nullable by using the '!' operator, or as nullable by using the '?' operator. This makes it easier to detect and prevent null reference errors, making your code safer and more robust.
- Non-nullable variables
- Nullable variables
- Non-null assertions (! operator)
- The ?? operator
Non-nullable variables: Variables declared without a '?' operator are non-nullable by default and cannot be assigned a null value. For example:
String name = "Pradeep";
Nullable variables: Variables declared with a ? operator are nullable and can be assigned a null value. For example:
Non-null assertions (! operator): The '!' operator is used to assert that a variable is not null. For example:
String name = "Pradeep"; print(name!.length);
The ?? operator: The ?? operator is used to provide a default value if a variable is null. For example:
String? profession; print(profession ?? "Not Provided");
By using null safety, you can write safer and more robust code in Flutter and prevent null reference errors.
Post a Comment