Error: Non-nullable variable 'mockBuildContext' must be assigned before it can be used

Error: Non-nullable variable 'mockBuildContext' must be assigned before it can be used

我已经在 setUp() 方法中分配了变量,但仍然抛出错误。如果我使 MockBuildContext 可以为空,则测试 运行 成功,但这不是正确的方法。有什么我遗漏的或建议更好的方法来解决这个问题。

查看我的代码:

void main(){

  MockBuildContext mockBuildContext;
  setUpGetIt(testing: true);

  setUp((){
    mockBuildContext = MockBuildContext();
  });

  group("banks test", (){

    test("Calling fetchAllBanks returns instance of BanksModel list", () async {

      banksBloc.init(mockBuildContext);
      await banksBloc.fetchAllBanks();
      banksBloc.allBanks?.listen((event) {
        expect(event, isInstanceOf<List<BanksModel>>);
      });

    });


  });
}

我的错误日志:

C:\Src\flutter\bin\flutter.bat --no-color test --machine --start-paused test\unit_test\system\bank_configuration\banks_test.dart
Testing started at 18:52 ...
test/unit_test/system/bank_configuration/banks_test.dart:24:22: Error: Non-nullable variable 'mockBuildContext' must be assigned before it can be used.
      banksBloc.init(mockBuildContext);
                     ^^^^^^^^^^^^^^^^

添加问号 MockBuildContext? 使其可为空或初始化它,如果它是 non-nullable,或在开始 late MockBuildContext mockBuildContext;

中添加 late 关键字

您可以使用声明初始化它

MockBuildContext mockBuildContext = MockBuildContext();

或者您可以在声明前添加late并像在设置函数中那样初始化它

late MockBuildContext mockBuildContext;