简体   繁体   English

Flutter Bloc 测试“bloc.add” null 安全问题

[英]Flutter Bloc test "bloc.add" null safety issue

I have a flutter bloc_test which is failing due to recent upgrades in Flutter involving null safety.我有一个 flutter bloc_test 由于 Flutter 最近升级涉及 null 安全而失败。

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"我在“bloc.add”行得到错误

"The method 'add' can't be unconditionally invoked because the receiver can be 'null'" “方法‘add’不能被无条件调用,因为接收者可以是‘null’”

Any ideas?有任何想法吗?

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)我通过铸造 bloc 类型来修复它(因为 act/bloc 是 Object? 类型)

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

Have a good day.祝你有美好的一天。

Kia Kaha,起亚卡哈,

Mike Smith迈克·史密斯

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))));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM