116

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
  • 175,842
  • 51
  • 533
  • 380
RCvaram
  • 3,901
  • 3
  • 16
  • 32

8 Answers8

156

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? foo; // Nullable String

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

Solutions:

You need to find out where you're using the bang operator in your code. Once you are there, you can use any of the following solutions:

  • Use a local variable

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

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

To answer your question:

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

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
  • 175,842
  • 51
  • 533
  • 380
33

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
  • 571
  • 5
  • 11
  • 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? – Lakkini 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
27

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
  • 175,842
  • 51
  • 533
  • 380
RCvaram
  • 3,901
  • 3
  • 16
  • 32
  • 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
7

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

Shreyas
  • 111
  • 1
  • 7
6

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
  • 73,993
  • 25
  • 133
  • 124
6

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
  • 7,067
  • 2
  • 33
  • 58
2

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.

1

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

Previously: UserRepository? userRepository;

Replace it with: late UserRepository userRepository;

ncutixavier
  • 67
  • 1
  • 2