Flutter Bloc test "bloc.add" null safety issue

739 views Asked by At

I have a flutter bloc_test which is failing due to recent upgrades in Flutter involving null safety.

I have the following code

blocTest('get the usecase name',
        build: () {
          when(() => mockGetUseCaseName(any()))
              .thenAnswer((_) async => Right(name));
          return bloc;
        },
        act: (bloc) => bloc.add(GetUseCaseName(name)),
        verify: (_) => verify(
            () => mockGetUseCaseName(Params(string: name))));

And I get the error on the line "bloc.add"

"The method 'add' can't be unconditionally invoked because the receiver can be 'null'"

Any ideas?

2

There are 2 answers

0
francisco gomes On BEST ANSWER

the most correct solution would be to make the data type explicit

Before:

blocTest('get the usecase name',
    build: () {
      when(() => mockGetUseCaseName(any()))
          .thenAnswer((_) async => Right(name));
      return bloc;
    },
    act: (bloc) => bloc.add(GetUseCaseName(name)),
    verify: (_) => verify(
        () => mockGetUseCaseName(Params(string: name))));

after:

blocTest<ClassBloc, ClassState>('get the usecase name',
    build: () {
      when(() => mockGetUseCaseName(any()))
          .thenAnswer((_) async => Right(name));
      return bloc;
    },
    act: (bloc) => bloc.add(GetUseCaseName(name)),
    verify: (_) => verify(
        () => mockGetUseCaseName(Params(string: name))));
0
MikeSmith On

I found the answer - for any others out there with the same issue. I fixed it by casting the bloc type (because act/bloc is of Object? type)

act: (bloc) => cast<UseCaseBloc>(bloc).add(GetUseCaseName(name))

Have a good day.

Kia Kaha,

Mike Smith