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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)