为什么我在 Flutter 测试期间使用 rootBundle.load 时会收到“Null checkoperatorusedonanullvalue”的信息?

Jef*_*eet 4 dart flutter flutter-test dart-null-safety

我搜索了很长一段时间,没有在 SO 或其他网站上找到解决此问题的明确解决方案。

我有一个颤振测试:

test('Create Repo and Read JSON', () {
  Repository repository = CreateRepository();
  ...
}
Run Code Online (Sandbox Code Playgroud)

CreateRepository()最终调用一个方法,代码如下:

var jsonString = await rootBundle.loadString(vendorDataFilePath);
Run Code Online (Sandbox Code Playgroud)

这会导致错误:Null check operator used on a null value

我执行的代码均未使用空检查运算符 ( !),那么此错误来自何处以及如何修复它?

Jef*_*eet 10

在调试模式下运行测试后,我发现错误实际上是在asset_bundle.dartFlutter 本身中,而不是在我的代码中。

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

这是instance!导致错误的原因,因为instance此时实际上为 null,因此 null 检查运算符 ( !) 失败。

不幸的是,这并没有像我们通常从 Flutter 中获得的漂亮的描述性错误消息,而是直接从 Dart 中得到更加神秘的错误描述。在我的例子中,根本原因是测试中需要额外的调用以确保instance初始化。

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