迁移到具有多个环境和共享首选项的 bloc >= 7.2.0

MIgrating to bloc >= 7.2.0 with multiple enevts and shared preferences

我正在处理使用 >=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)');
    }
  }
}

我该怎么做?

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

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
 }
}