gpt4 book ai didi

flutter - 为什么在 Flutter 测试期间使用 rootBundle.load 会得到 "Null check operator used on a null value"?

转载 作者:行者123 更新时间:2023-12-05 00:43:30 26 4
gpt4 key购买 nike

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

我有一个 Flutter 测试:

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

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

var jsonString = await rootBundle.loadString(vendorDataFilePath);

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

我执行的代码都没有使用空检查运算符 (!) 那么这个错误是从哪里来的,我该如何解决?

最佳答案

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

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

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

关于flutter - 为什么在 Flutter 测试期间使用 rootBundle.load 会得到 "Null check operator used on a null value"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69816543/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com