0

我正在使用 pre >=7.2.0 bloc 版本创建的登录页面,我在迁移此 AuthBloc 时遇到问题,因为它具有多个事件和共享首选项。

class AuthBloc extends Bloc<AuthEvent, AuthStates> {
  AuthBloc() : super(Initialization());

  Stream<AuthStates> mapEventToState(AuthEvent event) async* {
    yield WaitingAuth();
    switch (event.runtimeType) {
      case InitEvent:
        SharedPreferences prefs = await SharedPreferences.getInstance();
        bool login = prefs.getBool('login');
        if (login == null || !login) {
          prefs.clear();
          yield Initialization();
          break;
        } else {
          String token = prefs.getString('token');
          String tokenJWT = prefs.getString('tokenJWT');
          if (token == null ||
              tokenJWT == null ||
              token.isEmpty ||
              tokenJWT.isEmpty) {
            yield Initialization();
          } else {
            setToken(token);
            setJWTToken(tokenJWT);
            final response = await Api.getAccount();
            if (response is Account) {
              final sensorResponse = await Api.getDevices();
              if (sensorResponse is List<Sensor>) {
                yield SuccessAuth(account: response, sensors: sensorResponse);
              } else {
                yield SuccessAuth(account: response, sensors: []);
              }
            } else {
              yield Initialization();
            }
          }
        }break;
      default:
        SentryCapture.error(
            loggerName: 'AuthBloc',
            environment: 'switch',
            message: 'unhandled event($event)');
    }
  }
}

我该怎么做?

4

1 回答 1

0

使用 flutter bloc >= 7.2.0,您必须使用新的 on<Event> API并将您的替换yieldemit. 这是一个小例子。

MyBloc() : super (MyInitialState()) {
 on<MyEvent1>((event, emit) => emit(MyState1()));
 on<MyEvent2>((event, emit) => emit(MyState2()));
}

对于您的情况,请执行以下操作。

AuthBloc() : super(Initialization()) {
 on<AuthEvent>((event, emit) {
  emit(WaitingAuth());
  // Your logic
 }
}
于 2022-02-28T11:37:32.317 回答