When programming an App in Flutter, you often come across “Null Safety”, which was introduced by default in Flutter version 2.

What is Null Safety?

Null Safety prevents a variable from being uninitialized and therefore having a value of null.

This means that all variables must be initialized before they are used once they are declared.

If the variable is not initialized, an error will occur.

Why is Null Safety enabled by default?

Null Safety is enabled by default for three main reasons:

  • Reduces bugs: prevents crashes caused by unexpected null values.
  • Improves code: makes the code clearer and more readable.
  • Increases stability: makes the app more reliable and robust.

So I can’t use uninitialized variables?

The only way to declare that a variable can be null, and therefore inhibit Null Safety, is to add the ? operator after the type of the declared variable:

String? name

This declares a variable named name that can be either a String or null.

When is it necessary to disable Null Safety?

Let’s see a practical example: I have a class where I had to declare a parameter by disabling Null Safety.

Class Class{
...
String ? variable;
...
}

I need to call this parameter inside the Text Widget:

Text(class.variabile)

The Text Widget expects a data of type String and generates the following error “The argument type ‘String’ can’t be assigned to the parameter type ‘String'”

Flutter error "The argument type 'String' can't be assigned to the parameter type 'String'"
“The argument type ‘String’ can’t be assigned to the parameter type ‘String'”

Fix: Add a default text if the variable is null:

Text(class.variable ?? "Default text if variable is null")