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;

Share:
368
Jarin Rocks
Author by

Jarin Rocks

Updated on January 04, 2023

Comments

  • Jarin Rocks
    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
    Jarin Rocks over 1 year
    I do have initialized check my code
  • Akhlaq Shah
    Akhlaq Shah over 1 year
    not 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
    Jarin Rocks over 1 year
    yes adding late keyword seems to be a better approach