Error: Non-nullable variable 'mockBuildContext' must be assigned before it can be used
368
Solution 1
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;
Solution 2
you can either initialize it with the declaration
i.e MockBuildContext mockBuildContext = MockBuildContext();
or you can add late
before the declaration and initialize it as you are doing in the setup function
i.e late MockBuildContext mockBuildContext;
Author by
Jarin Rocks
Updated on January 04, 2023Comments
-
Jarin Rocks 10 months
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); 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>>); }); }); }); }
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. banksBloc.init(mockBuildContext); ^^^^^^^^^^^^^^^^
-
Jarin Rocks over 1 yearI do have initialized check my code
-
Akhlaq Shah over 1 yearnot like this, you have to initialize while declaring the variable. It's because of null-safety. Just add a question mark the error will be solved. or add late keyword in start
late MockBuildContext mockBuildContext;
-
Jarin Rocks over 1 yearyes adding late keyword seems to be a better approach