Search code examples
flutterdartflutter-testdart-null-safety

Why am I getting "Null check operator used on a null value" from using rootBundle.load during a Flutter test?


I searched for quite a while and didn't find a clear solution to this issue on SO or other sites.

I have a Flutter test:

test('Create Repo and Read JSON', () {
  Repository repository = CreateRepository();
  ...
}

CreateRepository() eventually calls a method with the following code:

var jsonString = await rootBundle.loadString(vendorDataFilePath);

This results in the error: Null check operator used on a null value

None of my executed code was using a null check operator (!) so where is this error coming from and how do I fix it?


Solution

  • After running the test in Debug mode, I found the error is actually in asset_bundle.dart within Flutter itself, not from my code.

    final ByteData? asset =
        await ServicesBinding.instance!.defaultBinaryMessenger.send('flutter/assets', encoded.buffer.asByteData());
    

    It's the instance! that causes the error because instance is actually null at this point, so the null check operator (!) fails.

    Unfortunately, rather than a nice descriptive error message like we normally get from Flutter, this results in a more cryptic error description directly from Dart. The root cause in my case was that an extra call is required in the test to make sure instance gets initialized.

    test('Create Repo and Read JSON', () {
      // Add the following line to the top of the test
      TestWidgetsFlutterBinding.ensureInitialized(); // <--
      Repository repository = CreateRepository();
      ...
    }