The “Null check operator used on a null value” error occurs in flutter apps when you unintentionally access a variable that has a null value. For example, if you’re using a variable that expect true or false value as a condition on a widget, if the variable is null, it will throw a runtime error. If null safety is disabled, it can be very cumbersome to debug. Flutter 2.0 and later version support null-safety which makes this error easy to debug because the compiler gives a clear hint of the underlying variable causing the null value error. Below is what the underlying dart language says…
How do you fix null check operator used on a NULL value?
Example of flutter null value used in a condition.
import 'dart:ffi';
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
Bool? isFalse = null;
@override
Widget build(BuildContext context) {
return Scaffold(
// this willl cause an error since the variable has a null value
body: isFalse ? Text(
'flutter tutorials',
) :
Text(
'dart tutorials',
),
);
}
}
Now if I run the above application, the expected error in layman perspective should be “Conditions must have a static type of ‘bool’”. But below is what flutter says…
Running Gradle task 'assembleDebug'...
✓ Built build/app/outputs/flutter-apk/app-debug.apk.
Installing build/app/outputs/flutter-apk/app.apk...
Waiting for SM J710F to report its views...
D/vndksupport(29495): Loading /vendor/lib/hw/android.hardware.graphics.mapper@2.0-impl.so from current namespace instead of sphal namespace.
Debug service listening on ws://127.0.0.1:39899/9RorUiKtUb4=/ws
Syncing files to device SM J710F...
D/ViewRootImpl@4ac1ef4[MainActivity](29495): MSG_RESIZED_REPORT: frame=Rect(0, 0 - 720, 1280) ci=Rect(0, 48 - 0, 582) vi=Rect(0, 48 - 0, 582) or=1
D/ViewRootImpl@4ac1ef4[MainActivity](29495): MSG_WINDOW_FOCUS_CHANGED 1
V/InputMethodManager(29495): Starting input: tba=android.view.inputmethod.EditorInfo@3049fea nm : com.sivaram.login_template ic=null
D/InputMethodManager(29495): startInputInner - Id : 0
I/InputMethodManager(29495): startInputInner - mService.startInputOrWindowGainedFocus
D/InputTransport(29495): Input channel constructed: fd=96
V/InputMethodManager(29495): Starting input: tba=android.view.inputmethod.EditorInfo@aad92db nm : com.sivaram.login_template ic=null
D/InputMethodManager(29495): startInputInner - Id : 0
D/ViewRootImpl@4ac1ef4[MainActivity](29495): MSG_RESIZED: frame=Rect(0, 0 - 720, 1280) ci=Rect(0, 48 - 0, 0) vi=Rect(0, 48 - 0, 0) or=1
D/ViewRootImpl@4ac1ef4[MainActivity](29495): Relayout returned: old=[0,0][720,1280] new=[0,0][720,1280] result=0x1 surface={valid=true 3791374336} changed=false
D/libGLESv2(29495): STS_GLApi : DTS, ODTC are not allowed for Package : com.sivaram.login_template
════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
Null check operator used on a null value
Login file:///home/kadavul/IdeaProjects/myapp/lib/main.dart:8:15
════════════════════════════════════════════════════════════════════════════════════════════════════
V/InputMethodManager(29495): Starting input: tba=android.view.inputmethod.EditorInfo@a0ff0af nm : com.sivaram.login_template ic=null
D/InputMethodManager(29495): startInputInner - Id : 0
I/InputMethodManager(29495): startInputInner - mService.startInputOrWindowGainedFocus
D/InputTransport(29495): Input channel constructed: fd=87
D/InputTransport(29495): Input channel destroyed: fd=96
D/SurfaceView(29495): windowStopped(true) false 77b9092 of ViewRootImpl@4ac1ef4[MainActivity]
D/SurfaceView(29495): BG show() Surface(name=Background for - SurfaceView - com.sivaram.login_template/com.sivaram.login_template.MainActivity@77b9092@0) io.flutter.embedding.android.FlutterSurfaceView{77b9092 V.E...... ........ 0,0-720,1280}
D/SurfaceView(29495): surfaceDestroyed 1 #1 io.flutter.embedding.android.FlutterSurfaceView{77b9092 V.E...... ........ 0,0-720,1280}
V/InputMethodManager(29495): Starting input: tba=android.view.inputmethod.EditorInfo@a78fcbc nm : com.sivaram.login_template ic=null
D/InputMethodManager(29495): startInputInner - Id : 0
I/InputMethodManager(29495): startInputInner - mService.startInputOrWindowGainedFocus
D/InputTransport(29495): Input channel constructed: fd=91
D/InputTransport(29495): Input channel destroyed: fd=87
D/SurfaceView(29495): windowStopped(false) true 77b9092 of ViewRootImpl@4ac1ef4[MainActivity]
D/SurfaceView(29495): BG show() Surface(name=Background for - SurfaceView - com.sivaram.login_template/com.sivaram.login_template.MainActivity@77b9092@1) io.flutter.embedding.android.FlutterSurfaceView{77b9092 V.E...... ........ 0,0-720,1280}
V/Surface (29495): sf_framedrop debug : 0x4f4c, game : false, logging : 0
D/SurfaceView(29495): surfaceCreated 1 #1 io.flutter.embedding.android.FlutterSurfaceView{77b9092 V.E...... ........ 0,0-720,1280}
D/mali_winsys(29495): EGLint new_window_surface(egl_winsys_display *, void *, EGLSurface, EGLConfig, egl_winsys_surface **, egl_color_buffer_format *, EGLBoolean) returns 0x3000, [720x1280]-format:1
D/SurfaceView(29495): surfaceChanged (720,1280) 1 #1 io.flutter.embedding.android.FlutterSurfaceView{77b9092 V.E...... ........ 0,0-720,1280}
D/SurfaceView(29495): BG destroy() Surface(name=Background for - SurfaceView - com.sivaram.login_template/com.sivaram.login_template.MainActivity@77b9092@0) io.flutter.embedding.android.FlutterSurfaceView{77b9092 V.E...... ........ 0,0-720,1280}
D/ViewRootImpl@4ac1ef4[MainActivity](29495): Relayout returned: old=[0,0][720,1280] new=[0,0][720,1280] result=0x3 surface={valid=true 3791374336} changed=false
D/ViewRootImpl@4ac1ef4[MainActivity](29495): MSG_RESIZED_REPORT: frame=Rect(0, 0 - 720, 1280) ci=Rect(0, 48 - 0, 0) vi=Rect(0, 48 - 0, 0) or=1
V/InputMethodManager(29495): Starting input: tba=android.view.inputmethod.EditorInfo@7ed1445 nm : com.sivaram.login_template ic=null
D/InputMethodManager(29495): startInputInner - Id : 0
I/InputMethodManager(29495): startInputInner - mService.startInputOrWindowGainedFocus
D/InputTransport(29495): Input channel constructed: fd=92
D/InputTransport(29495): Input channel destroyed: fd=91
D/SurfaceView(29495): windowStopped(true) false 77b9092 of ViewRootImpl@4ac1ef4[MainActivity]
D/SurfaceView(29495): BG show() Surface(name=Background for - SurfaceView - com.sivaram.login_template/com.sivaram.login_template.MainActivity@77b9092@1) io.flutter.embedding.android.FlutterSurfaceView{77b9092 V.E...... ........ 0,0-720,1280}
D/SurfaceView(29495): surfaceDestroyed 1 #1 io.flutter.embedding.android.FlutterSurfaceView{77b9092 V.E...... ........ 0,0-720,1280}
Example 2 – When I run an app, below is the Error Message:
══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞════════════════
The following _CastError was thrown building Home(dirty, state: _HomeState#1dc98):
Null check operator used on a null value
The relevant error-causing widget was:
Home Home:file:///C:/flutter_apps/myflutterapp/lib/main.dart:13:16
When the exception was thrown, this was the stack:
#0 _HomeState.build (package:myflutterapp/main.dart:48:37)
Cause of the above error:
The main cause of the above error is that a null check (!) operator was used on a null value. When you use this operator on a null value, flutter will throw an error unless you use a condition.
//Nullable String, meaning a null value can be assign to it
String? firstName;
//Error: Null check operator used on a null value
int firstNameLength = firstName!.lenght;
The above “firstName” variable holds a value of null. And we’re checking the length of the string characters it holds on the next line with a null check operator (!). This will throw an error because the length property can’t be called on a null value. But this is not big deal, we can solve this in different ways:
Solution 1: First use a condition to check if the value is not null before calling a method or property on it:
//nullable variable
String? firstName;
int theLength = 0;
if(firstName != null){
theLength = firstName!.length;
}else{
theLength = 0; //return 0 if firstName is null
}
print(theLength); //output: 0
Above, we used a condition to check if the String variable “firstName”
is null or not before we call the length property. This way, we will never get an error saying “null check operator used on a null value.” You could use the same nullable variable on a Text()
widget by doing:
String? firstName; //nullable value
Text(firstName?? "User first name is null"),
Here, the Text()
widget takes in a string as it first argument which is the string to be displayed. So, we passed the nullable variable “firstName”
to it but notice we’re checking if it’s null with ?? operator. If “firstName”
is null, then we have a fallback text of “User first name is null”. The ?? symbol used above act as a null check condition. Without the operator it will throw an error similar to “null check operator used on a null value the relevant error-causing widget was listview or Text.” Other examples are below:
firstName != null?
//if the firstName variable is not null
Container(
child: Text(firstName == "flutter and dart tutorials"?"flutter":"dart"),
):
//if firstName is null
Card(
child: Text("Error while getting data from network."),
)
Here, based on the value of “firstName”
variable, a different widget will be displayed.
Solution 2: Using a default operator on null values
//nullable function: it could return null or not
int? calculateLengeth(){
return null; //return null for now;
}
//if calculateLengeth() returns null value, it sets value to 20
int len = calculateLengeth() ?? 20;
print(len); //output: 20
From the above, we have set a default value of 20. If the method calculateLengeth()
returns null, the variable “len”
will be assign a 20 because that’s the default value we have set using the ?? default-operator.
Solution 3: Using fallback operator
We have already used the fallback operator in the previous examples. But you can also use it to set default values for null values.
//nullable value
String? firstName;
// this value will be assigned only when the variable is null
firstName ??= "Fallback Value";
//Output: Fallback Value
Print(firstName);
The way we have used the fallback operator here is little different from the previous examples. The “fristName”
variable was first declared no value assigned, meaning it will hold a null value. Then we used the fallback and the assignment operator to assign a value to the variable. But here it will check if “firstName”
is null first before the value will be assigned to it, this will solve the above null value error in Flutter or Dart.
What is null check operator?
Null check operator is used as a condition on a nullable variable to provide a fallback value. When it used, it will return the value of it left-hand operation/value if it isn’t null else it will evaluate the right-hand operand and returns it value/result.
Example:
String? websiteName;
Text(websiteName ?? “DartAndFlutter.com”)
Here, the “null check operator” acts as a condition to either evaluate the left-hand side or right-hand-side value. It will first check if the variable “websiteName”
is not null then it will return it value. But if its null, then it will return “DartAndFlutter.com”
You can also use it in variable assignment as shown below.
String? firstName;
String fullName = firstName ?? “John ”+ “Doe”;
How do you check for null conditions?
To check for null in a condition use an “if statement” or ternary operator in a widget. Null values can be annoying when you have a big project that does not use optional values.
For example in a method you could use “if statement” as:
String? username;
String getUsername(){
// check for null value in a condition and decide what to return based on the project requirement
If(username!=null){
return username;
}
else{
return “username is null”;
}
}
You can also use a ternary operator to check for null values both in widgets and methods.
String? Username;
Container(
Child: (Username !=null) ?
Text(Username) :
Text(“username is null”)
)
This Post Has One Comment
Comments are closed.