185

I am new to Flutter

I got this error when I run my simple flutter APP. I could not figure out why this error occurred.

Error

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/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/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?

CopsOnRoad
  • 237,138
  • 77
  • 654
  • 440
Sivaram Rasathurai
  • 5,533
  • 3
  • 22
  • 45

13 Answers13

265

Don't downgrade Flutter

Problem:

This error occurs when you use a bang 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();
      },
    )
    
CopsOnRoad
  • 237,138
  • 77
  • 654
  • 440
  • 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. – Mohammad Aamir Feb 07 '23 at 11:24
  • 2
    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. – Luke Hutchison Mar 10 '23 at 22:22
  • 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. – Dennis Ashford Jun 11 '23 at 14:03
  • 1
    @DennisAshford Something like `Future> _listOfInt() async => [0, 1]`. – CopsOnRoad Jun 12 '23 at 20:36
  • @LukeHutchison What's the workaround for that case? I think I'm having a related issue. – Django Jul 09 '23 at 20:51
  • @Django 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. – Luke Hutchison Jul 10 '23 at 21:35
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());}
Anil Bhomi
  • 691
  • 7
  • 12
  • 1
    same for the path_provider package – dilshan Oct 20 '21 at 07:50
  • Thank you so much @AaNeal O'Neal the application started as well, I just want to know what that means? can you explain, please? – CTMA Dec 23 '21 at 15:50
  • 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. – Anil Bhomi Dec 27 '21 at 06:09
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

CopsOnRoad
  • 237,138
  • 77
  • 654
  • 440
Sivaram Rasathurai
  • 5,533
  • 3
  • 22
  • 45
  • 2
    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). – Christoph P Nov 26 '20 at 18:52
  • 2
    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. – Tunnelvisie Feb 27 '21 at 12:31
  • 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? – A M Jun 05 '21 at 16:37
13

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

Shreyas
  • 311
  • 2
  • 9
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.

Pranav Kasetti
  • 8,770
  • 2
  • 50
  • 71
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
Peter Haddad
  • 78,874
  • 25
  • 140
  • 134
5

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.

fares hassan
  • 136
  • 2
  • 5
4

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

Previously: UserRepository? userRepository;

Replace it with: late UserRepository userRepository;

ncutixavier
  • 455
  • 5
  • 4
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(_) =>...,
 );
Naimul Kabir
  • 434
  • 6
  • 13
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 ?? ""
Ayush Sth
  • 317
  • 6
  • 11
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
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;.

Hamed
  • 5,867
  • 4
  • 32
  • 56
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

Doan Bui
  • 3,572
  • 25
  • 36