Null check operator used on a null value
Asked Answered
H

15

204

I got this error when I run my simple flutter app:

Null check operator used on a null value

My code in main.dart

import 'package:flutter/material.dart';
import './ui/login.dart';

void main() {
  
  runApp(new MaterialApp(
    title: "Login Template",
    home: new Login(),
  ));
}

My code in login.dart

import 'package:flutter/material.dart';

class Login extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return new LoginState();
  }
}

class LoginState extends State<Login> {
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text("Login"),
        centerTitle: true,
        backgroundColor: Colors.blueAccent.shade50,
      ),
      backgroundColor: Colors.blueGrey,
      body: new Container(

      ),
    );
  }
}

Error trace of the code

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/[email protected] 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/login_template/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}

My flutter doctor ouput


fatal: ambiguous argument 'HEAD': unknown revision or path not in the working tree.
Use '--' to separate paths from revisions, like this:
'git <command> [<revision>...] -- [<file>...]'
Doctor summary (to see all details, run flutter doctor -v):
Failed to find the latest git commit date: VersionCheckError: Command exited with code 128: git -c log.showSignature=false log -n 1 --pretty=format:%ad --date=iso
Standard out: 
Standard error: fatal: your current branch 'master' does not have any commits yet

Returning 1970-01-01 05:30:00.000 instead.
[✓] Flutter (Channel unknown, 0.0.0-unknown, on Linux, locale en_US.UTF-8)
 
[✓] Android toolchain - develop for Android devices (Android SDK version 30.0.2)
[✓] Android Studio (version 4.0)
[!] VS Code (version 1.50.0)
    ✗ Flutter extension not installed; install from
      https://marketplace.visualstudio.com/items?itemName=Dart-Code.flutter
[✓] Connected device (1 available)

! Doctor found issues in 1 category.

Can anyone provide a solution for this?

Hydrometallurgy answered 9/10, 2020 at 10:52 Comment(9)
execute flutter doctor in the terminalLegged
Could you copy paste the exact error trace? Maybe we can find where the problem is being causePrisoner
added error traceHydrometallurgy
are u using the stable channel or master?Legged
I think it was masterHydrometallurgy
Does it end there? It was about to show what widget caused the error. There must be more. And have you built another app using flutter? It might just be a problem with the SDK config, which you can delete and downloadPrisoner
This may be a problem related to the new version. Please add flutter doctor result. Same issue in here: github.com/dart-lang/sdk/issues/43695Indican
It was my mistake. I have added full error trace nowHydrometallurgy
@Akif, I added flutter doctor resultHydrometallurgy
S
299

Don't downgrade Flutter

Problem:

This error occurs when you use a non-null assertion operator (!) on a nullable instance which wasn't initialized.

For example:

String? string; // Nullable String

void main() {
  var len = string!.length; // Runtime error: Null check operator used on a null value
}

Solutions:

Open the logs and there must be a line pointing to a file in your project where the error occurred:

Null check operator used on a null value

#0 main (package:example/main.dart:22:16)

Once you are there, you can use any of the following ways to fix it:

  • Use a local variable

    var s = string;
    if (s != null) {
      var len = s.length; // Safe 
    }
    
  • Use ?. and ??

    var len = string?.length ?? 0; // Provide a default value if string was null.
    

The stack trace can also point to a file that doesn't belong to your project. For example:

1. For those who are using Navigator or MediaQuery

This error also occurs when you try to access a BuildContext asynchronously.

So, you should first check if the widget is mounted before accessing BuildContext.

Future<void> foo() async {
  // Some async operation
  await compute();  

  // Check `mounted` before accessing 'context'.
  if (mounted) {
    MediaQuery.of(context).size;
    Navigator.of(context).pop();  
  }
}

2. For those who are using Color

You're using

Colors.blueAccent.shade50

which doesn't have 50th shade. If you look into the source code, you'd find:

Color get shade50 => this[50]!; // <-- This bang operator is causing the error.

To solve this error, you should use some other color which is not null, maybe the 100th shade.

Colors.blueAccent[100]
// or
Colors.blue.shade100

3. For those who are using FutureBuilder/StreamBuilder:

You can solve the error in two ways:

  • Specify a type to your FutureBuilder/StreamBuilder

    FutureBuilder<List<int>>( // <-- type 'List<int>' is specified.
      future: _listOfInt(),
      builder: (_, snapshot) {
        if (snapshot.hasData) {
          List<int> myList = snapshot.data!; // <-- Your data
        }
        return Container();
      },
    )
    
  • Use as to downcast Object to your type, say a List or Map.

    FutureBuilder(
      future: _listOfInt(),
      builder: (_, snapshot) {
        if (snapshot.hasData) {
          var myList = snapshot.data! as List<int>; // <-- Your data using 'as'
        }
        return Container();
      },
    )
    
Salic answered 15/6, 2021 at 16:50 Comment(6)
One more important thing to note here is never uncheck Unhandled Exception breakpoint. If you uncheck you will not get exact line number in such error case.Fango
One more case worth mentioning -- if you try to access widget in the constructor of a StatefulWidget's State class, you'll get this null check error.Manthei
Would you be able to show what your future _listOfInt() would look like in use of the FutureBuilder here? Not exactly how to initialize that.Moreira
@DennisAshford Something like Future<List<int>> _listOfInt() async => [0, 1].Salic
@LukeHutchison What's the workaround for that case? I think I'm having a related issue.Lunn
@Lunn You can't directly work around it. You can't access the associated widget while initState is running (if you look at the code, _widget is not set yet when initState is running, because the whole point of initState is to initialze. The widget getter returns _widget!, which is where the error comes from). You can only access widget from build. If you have to run your code before build, you may or may not be able to access widget from didChangeDependencies, which runs after init, in a different phase of the layout and rendering process -- I haven't checked that.Manthei
C
41

Any one who are using get_it package and having similar issue, here is the most simple solution. just add WidgetsFlutterBinding.ensureInitialized(); at the top of main function.

Change your main function like this :

Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await di.init()
runApp(MyApp());}
Counterstatement answered 13/6, 2021 at 8:3 Comment(3)
same for the path_provider packageIte
Thank you so much @AaNeal O'Neal the application started as well, I just want to know what that means? can you explain, please?Bailiff
Basically, it returns an instance of the WidgetsBinding, creating and initializing it if necessary. If one is created, it will be a WidgetsFlutterBinding. If one was previously initialized, then it will at least implement WidgetsBinding. You only need to call this method if you need the binding to be initialized before calling runApp.Counterstatement
H
33

Prefer CopsOnRoad answer and only downgrade if that didn't work.

Steps that we need to solve the above problem as follow


 - flutter channel stable 
 - flutter upgrade
 - flutter pub cache repair //To perform a clean reinstall of the packages in your system cache, use pub cache repair
 - flutter clean //flutter clean will delete the /build folder

When I tried flutter channel stable . I got another error since I had two flutters one is from snapd and another one is from git clone method.

then, I configured the SDK with the git clone. Finally, I used Git cloned SDK flutter to do all commands as follow

flutter channel stable 
 - ~/flutter/bin/flutter upgrade
 - ~/flutter/bin/flutter pub cache repair //To perform a clean reinstall of the packages in your system cache, use pub cache repair
 - ~/flutter/bin/flutter clean //flutter clean will delete the /build folder

Hydrometallurgy answered 9/10, 2020 at 12:25 Comment(3)
In my case, this didn't solve the problem, but the error message was clearer after upgrading/cleaning so I could find the "true cause" (missing localization for the cupertino widgets).Montmartre
Is there any way to subvert this message when you need to run on the beta channel? I have a similar issue, but I'm running on beta for the MacBook M1, so can't really use the stable channel.Naumann
I too cannot switch to a stable channel as my program relies on minimum sdk version 2.12.0 (or so I think is the issue I don't fully understand flutter yet) so I am running on the dev channel. So is there any way to deal with this issue without switching channels?Afterwards
I
14

For newbies like me to flutter, try restarting the app rather than hot reloading it.

Intervocalic answered 15/5, 2021 at 10:52 Comment(1)
that gonna took us like 3 minutes every time we debug!Remainder
C
9

Provider Anti-Patterns

If we get this error outside of our package, then we may need to look into how we are using third-party dependencies. In my case, Provider anti-patterns were causing issues.

The lifecycle of a Provider object is different from a regular widget because it can be unexpectedly re-created or not created at all depending on usage.

Example 1

I encountered a simple reproducible example when initialising a ChangeNotifierProvider outside of the create: block.

Good

ChangeNotifierProvider(
  create: (_) => ToDoContainerModel(),
  builder: (context, _) {
    return home;
}));

Bad

ChangeNotifierProvider(
  create: (_) => model,
  builder: (context, _) {
    return home;
}));

This is documented in the repository as an anti-pattern:

DON'T reuse an existing ChangeNotifier using the default constructor.

Example 2

Another anti-pattern that can cause similar side-effects is:

Do not use the .value constructor if you want to create an object, or you may otherwise have undesired side effects.

Good

ChangeNotifierProvider.value(
  create: (_) => MyModel(),
  child: ...
)

Bad

ChangeNotifierProvider.value(
  value: MyModel(),
  child: ...
)

Cause of error

sqflite databases should only have one call to openDatabase for consistency. Using ChangeNotifierProvider anti-patterns, I got this error because I was triggering openDatabase more than once. I thus triggered unhandled exceptions because sqflite internally returns null for openDatabase when we specify the same db path in repeated calls.

TIP: Check third-party documentation when you get this error outside of your package.

Cowie answered 21/8, 2021 at 21:33 Comment(0)
L
8

The issue might be related to the null safety that is getting integrated in dartlang. For now you can switch channels and use the stable channel:

flutter channel stable
flutter upgrade
Legged answered 9/10, 2020 at 11:15 Comment(4)
on stable channel, latest flutter, the firebase plugin throwing up this error here ` /// The user's unique ID. String get uid { return _data['uid']!; }`Rauwolfia
when listening to user changes and i print the latest user it throws me Null check operator used on a null value it leads to line from above comment in the user_info.dart fileRauwolfia
Thank you, but where exactly should I type this?Imbalance
In the terminalLegged
Z
6

This issue also occurs when you use a context that has already finished. For example, Navigator.pop(context), so you may check your code sequence again.

Zebulun answered 27/3, 2022 at 11:57 Comment(0)
W
4

On my side, I fixed it by using late instead of ?

Previously: UserRepository? userRepository;

Replace it with: late UserRepository userRepository;

Webb answered 31/5, 2022 at 18:38 Comment(1)
when I use late I got this error LateInitializationError: Field 'taskname' has not been initialized.Dioptric
U
4

There might be different reasons for this. But for me, the reason was GetX. If anyone using GetX, make sure that you add init parameter inside your GetX. Here's an example:

late final DemoController _controller= Get.put(()=>DemoController());

GetX(
    init: _controller, 
    builder(_) =>...,
 );
Urmia answered 17/12, 2022 at 5:24 Comment(1)
totally forgot to wrap material with Get thanks dude.Delinquency
H
3

If you are trying to set text with a nullable value then you can add this line to resolve this issue.

If the value of the name is null and you have to assign the nullable value then add

name ?? ""
Hebrew answered 1/9, 2022 at 4:47 Comment(0)
A
3

You are getting this error because you haven't initialise your GetxController. Please initialise your controller where you are initialising all other controllers on app start.

Initialise like this

  • Get.put(YourController()) immediately
  • Get.lazyPut(()=> YourController()) when you need it
Amelina answered 23/9, 2022 at 19:3 Comment(0)
M
2

Was having the same issue and it happened the error was a result of Cloud Firestore rules. I had set the rule on request.time and the timestamp.date had expired. So you can check on that and set the rule either allow read, write: if true; or allow read, write: if request.auth != null;.

Mackintosh answered 1/7, 2022 at 23:17 Comment(0)
J
1

If run console not show detail error line in code, you can use dubug to know exactly which line of code it failed. enter image description here

Jeromejeromy answered 12/8, 2023 at 12:23 Comment(0)
S
1

The very short summary answer to this:

Dart is null safe. This is good and a blessing, embrace the concept. Here is the essence of what that means:

  1. It requires you to declare if a variable is able to be null or not.

    String requiredString = 'This was required';

    String? nullableString;

  2. Sometimes the linter (your IDE) will give you errors and warnings because a nullable variable is being passed to something requiring a value.

debugPrint(nullableString); Will error.

To fix that you might put: debugPrint(nullableString!); But make sure your logic will ensure it won't arrive there null!

  1. Here's where things get really fun. You can use ? to say: "I don't know if this is null, only perform this function if it's not null."

Let's say you're trying to get a value from a Map and you don't want to crash if a value within the map isn't there.

Map carValues = {cars:{mustang: 25000, corvette: 36000}, vans:{vw: 12000, conversion: 22000}};

nullableString = carValues['trucks']?['peterbuilt'];

nullableString be null, but safely, because you don't have trucks in your map. If you didn't have the ? there between trucks and peterbuilt, the compiler would look for the key 'peterbuilt' in carValues['trucks'] which is null and since that's not possible, you get a crash. The ? makes that search conditional. If you wrote:

nullableString = carValues['trucks']!['peterbuilt']; You might fix the IDE linter warning, but since trucks isn't in your map you will error out.

If trucks WAS present, but just not peterbuilt it wouldn't error, because nullableString is nullable and peterbuilt not being there just gives null. It's the act of looking for something from nothing that errors, not just finding nothing. Maybe reread that sentence.

You would error if you wrote (IDE would warn)

requiredString = carValues['cars']?['porsche']; The value is null, but requiredString can't be null! In this case, the linter will ask you to write: requiredString = carValues['cars']!['porsche']!;

Null safety is an accountability partner to writing and ensuring good code. I like having nullable variables in my code and null safety keeps things safer while giving more options.

Sippet answered 8/9, 2023 at 21:20 Comment(0)
L
0

In addition to CopsOnRoad's answer, If you are using Global keys to send Form data to another screen you can use below method:

GlobalKey<FormState> _key = new GlobalKey();

var currentState = _key.currentState;
if (currentState != null) {
  currentState.validate();
  currentState.save(); // Safe
Lauraine answered 8/12, 2023 at 18:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.