0

我正在将我的项目迁移到新版本的 Flutter 并使用 BloC 包。如您所知,Bloc 已经更新并且它已经更改了大部分代码,所以现在我正在调整我的,但我有一些错误。

参数类型“Future Function(bool)”不能分配给参数类型“UserState Function(bool)”

主体可能正常完成,导致返回“null”,但返回类型可能是不可为空的类型。

前 :

  Stream<UserState> _validate(ValidateEvent event) async* {

    final successOrFailure = await services.validate();
    
    yield* successOrFailure.fold(
      (sucess) async* {
        final session = await services.getSession();
        yield* session.fold(
          (session) async* {
            yield UserSuccess(session);

            yield UserLogged(session);
          },
          (failure) async* {
            yield UserError(failure.message);
          },
        );
      },
      (failure) async* {
        yield UserError(failure.message);
      },
    );
  }

后 :

UserBloc({this.services}) : super(UserInitial()) {
    on<ValidateEvent>(_onValidate);
  }

void _onValidate(
    ValidateEvent event,
    Emitter<UserState> emit,
  ) async {

    final successOrFailure = await services.validate();
    
    emit(
      successOrFailure.fold(
        (success) async {
          final session = await services.getSession();
          emit(
            session.fold(
              (session) { // ! The body might complete normally, causing 'null' to be returned, but the return type is a potentially non-nullable type.
                emit(UserSuccess(session));

                emit(UserLogged(session));
              },
              (failure) { // ! The body might complete normally, causing 'null' to be returned, but the return type is a potentially non-nullable type.
                emit(UserError(failure.message));
              },
            ),
          );
        }, // ! The argument type 'Future<Null> Function(bool)' can't be assigned to the parameter type 'UserState Function(bool)
        (failure) { // ! The body might complete normally, causing 'null' to be returned, but the return type is a potentially non-nullable type.
          emit(UserError(failure.message));
        },
      ),
    );
  }

我需要在里面有那个异步,因为我再次调用了服务,关于身体,在我看来我必须以某种方式返回它,但我里面有一些逻辑,我不知道该怎么做。

4

1 回答 1

2

在这种情况下,您唯一可以emit做的是您的状态类型的实例UserState。与其尝试发出 Future,不如使用await它。

void _onValidate(
    ValidateEvent event,
    Emitter<UserState> emit,
  ) async {

    final successOrFailure = await services.validate();
    
    await successOrFailure.fold( // This will return FutureOr<Null>
      (success) async {
        final session = await services.getSession();
        session.fold( // This isn't asynchronous, so no need to await here
          (session) {
            emit(UserSuccess(session));

            emit(UserLogged(session));
          },
          (failure) {
            emit(UserError(failure.message));
          },
        );
      },
      (failure) {
        emit(UserError(failure.message));
      },
    );
  }
于 2022-01-24T16:06:12.373 回答