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


I have assigned the variable inside the setUp() method but still its throwing error. The test is running successfully if I made the MockBuildContext nullable but it is not the correct approach. Is there anything I missed out or suggest a better way to solve this.

See my code:

void main(){

  MockBuildContext mockBuildContext;
  setUpGetIt(testing: true);

    mockBuildContext = MockBuildContext();

  group("banks test", (){

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

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



My error log:

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.


add question mark MockBuildContext? to make it nullable or initialize it if it’s non-nullable, or add late keyword in start late MockBuildContext mockBuildContext;

Answered By – Akhlaq Shah

Answer Checked By – Mildred Charles (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *