Flutter 块:如何等待事件返回一些状态数据

bejyjqdl  于 2023-06-07  发布在  Flutter
关注(0)|答案(1)|浏览(319)

我试图将flutter_login小部件与块集成。下面是我使用的示例代码

BlocProvider(
      create: (ctx) => UserAuthenticationPageBloc(ctx),
      child: BlocListener<UserAuthenticationPageBloc, UserAuthenticationPageState>(
        listener: (context, state) {
          // not used at the moment
        },
        child: BlocBuilder<UserAuthenticationPageBloc, UserAuthenticationPageState>(
          builder: (context, state) {
            final bloc = context.read<UserAuthenticationPageBloc>();

            return FlutterLogin(onLogin: (loginData) async {
              bloc.add(SignIn(loginData: loginData));
              return state.loginMessage;
            }, onRecoverPassword: (email) async {
              bloc.add(RecoverPassword(email: email));
              return state.recoverPasswordMessage;
            });
          },
        ),
      ),
    )

这里是块文件

class UserAuthenticationPageBloc extends Bloc<UserAuthenticationPageEvent, UserAuthenticationPageState> {
  UserAuthenticationPageBloc(BuildContext context) : super(const UserAuthenticationPageState()) {
    on<SignIn>((event, emit) {
      try {
        emit(state.copyWith(signInStatus: SignInStatus.loading));

        User user = User(); // need to be replaced by async http call

        final GlobalBloc globalBloc = BlocProvider.of<GlobalBloc>(context);

        globalBloc.add(GlobalSignIn(user: user));
        emit(state.copyWith(loginMessage: 'some error', signInStatus: SignInStatus.failure));
      } catch (_) {
        //emit(CovidError("Failed to fetch data. is your device online?"));
      }
    });
    on<RecoverPassword>((event, emit) {
    });
  }
}

我想做的是添加一个事件来阻止,然后返回一条消息。flutter_login小部件将根据返回的消息显示小吃店。
如何在从状态中检索loginMessage之前等待bloc事件完成?或者我不应该把loginMessage放在state中?
谢谢你

olmpazwi

olmpazwi1#

您可以尝试在单独的参数中传递onLogin函数和onRecoverPassword函数和状态,并在FlutterLogin中检查onloginMessagerecoverPasswordMessage不为null。
我还认为你应该通过查看不同的示例来熟悉bloc,我建议在包本身的examples文件夹中https://github.com/felangel/bloc/tree/master/examples

相关问题