You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中Either的fold方法未执行问题求助

排查Either.fold方法未执行的问题

核心问题分析

你的代码里有两处关键错误导致fold逻辑看似被"跳过":

1. 登录方法中fold的回调是未执行的匿名函数

在signInWithGoogle方法里,你给fold传递的是返回匿名函数的箭头函数,这意味着分支内的逻辑根本不会被执行,而且方法最后直接返回Left(GeneralFailure()),完全忽略了Google登录的实际结果。

修复后的登录方法代码:

Future<Either<Failure, SignUpSuccess>> signInWithGoogle() async {
  try {
    final signUpResult = await googleRemoteDataSource.signInWithGoogle();

    // 去掉匿名函数包裹,直接在fold分支处理逻辑并返回结果
    return signUpResult.fold(
      (failure) {
        print("Got failure!");
        return Left(GeneralFailure());
      },
      (success) {
        return Right(success);
      },
    );
  } catch (e) {
    print("Caught exception! ${e.toString()}");
    return Left(GeneralFailure());
  }
}
  • 移除() =>的匿名函数包裹,让分支逻辑直接执行
  • 将fold的处理结果作为方法返回值,不再强制返回失败

2. Bloc中success分支的回调是未执行的匿名函数

在SignInBloc处理SignInWithGooglePressed事件时,successOrFailure.fold的success分支用匿名函数包裹了逻辑,导致emit(SignInWithGoogleLoaded())从未被调用,成功分支没有任何状态更新。

修复后的Bloc代码:

class SignInBloc extends Bloc<SignInEvent, SignInState> {
  final SignUpUseCases useCases;
  SignInBloc({required this.useCases}) : super(SignInInitial()) {
    on<SignInWithGooglePressed>((event, emit) async {
      emit(SignInWithGoogleLoading());

      Either<Failure, SignUpSuccess> successOrFailure =
          await useCases.signInWithGoogle();

      successOrFailure.fold(
        (failure) => emit(SignInError()),
        (success) {
          // 移除匿名函数,直接执行emit和后续业务逻辑
          emit(SignInWithGoogleLoaded());
          // 在这里处理创建本地用户、赋值用户名等逻辑
        },
      );
    });
  }
}
  • 去掉success分支的() =>包裹,直接执行emit操作和后续逻辑

额外说明

Widget部分代码无明显问题,修复上述两处错误后,Bloc的状态更新会正常触发BlocListener里的逻辑,你应该能看到对应的打印信息和页面导航行为。

内容的提问来源于stack exchange,提问作者kev_the_game.dev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 06:05:37