[Solved] Null check operator used on a null value

In this example, we are going to show you how to show you the cause and solution of the "Null check operator used on a null value" error in the Flutter App.

══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞════════════════
The following _CastError was thrown building Home(dirty, state: _HomeState#1dc88):
Null check operator used on a null value

The relevant error-causing widget was:
  Home Home:file:///C:/flutter_apps/testapp/lib/main.dart:13:16

When the exception was thrown, this was the stack:
#0      _HomeState.build (package:testapp/main.dart:44:27)

This error occurs when you add (!) Null check operator on Null value. For example:

String? str; //Nullable String
int length = str!.lenght; 
//Error: Null check operator used on a null value 

The operator (!) is used on null value "str". To solve this issue, see the different examples below:

String? str; //nullable value
int len = 0;
if(str != null){
    len = str!.length;
}else{
    len = 0; //return value if str is null
}

print(len); //output: 0

Here, we check if the "str" String variable is null or not before getting the length. If you are using the nullable value on Widget, then do like below:

String? str; //nullable value
Text(str ?? "String value is null"),

Here, if the "str" value is null, the Text will have the "String value is null" text, otherwise, it will have the value of the "str" variable. More examples are below:

str != null?
  Container( //if the str is not null
    child: Text(str == "hello"?"You have 1 message":"You haven't any message"),
  ):
  Card( //if str is null
     child: Text("Error while getting messages."),
  )

int? strlen(){ //nullable function: for example
    return null; //return null for now;
}
int len = strlen() ?? 3; //if strlen() returns null value, it sets value to 3
print(len); //output:  3

Here, we have set the default value to 3 using "??" default operator. If the strlen() returns the null value it will set value to 3.

Use the fallback operator to set a default value for null values before using the variable.

String? str; //nullable value
str ??= "Fallback Value";
print(str); //Output: Fallback Value

Here, "str" is null, and we set the fallback operator with fallback value in case of "str" is null. You need to do this before using it on the code.

You can use this method to handle Null values to escape the "Null check operator used on a null value" error in Flutter or Dart.

No any Comments on this Article


Please Wait...