Null check operator used on a null value Null check operator used on a null value flutter flutter

Null check operator used on a null value


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 Stringvoid 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]// orColors.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();  },)


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


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());}