Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Null check operator used on a null value

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

like image 862
RCvaram Avatar asked Oct 09 '20 10:10

RCvaram


People also ask

How would you handle a null check operator used on a NULL value flutter?

Solution 3: Using Fallback Operator: 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.

Which operator is used for null value?

The IS NULL operator is used to test for empty values (NULL values).

What is the null check?

A null indicates that a variable doesn't point to any object and holds no value. You can use a basic 'if' statement to check a null in a piece of code. Null is commonly used to denote or verify the non-existence of something.

WHAT IS null check operator in flutter?

before an expression, inserts a list into another only if it's not null. It helps add multiple values to our collection like List, Map, and Set. It is also called a Null check operator.


2 Answers

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());} 
like image 44
AaNeal O'Neal Avatar answered Sep 19 '22 14:09

AaNeal O'Neal


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();   }, ) 
like image 150
CopsOnRoad Avatar answered Sep 16 '22 14:09

CopsOnRoad