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

Time:03-01

I am working on a login page that was created with the pre >=7.2.0 bloc version and I am having issues migrating this AuthBloc because it has multiple events and shared preferences within.

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)');
    }
  }
}

How do I go about it?

CodePudding user response:

With flutter bloc >= 7.2.0 you have to use the new on< Event> API and replace your yield with emit. Here is a small example.

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

For your case do the following.

AuthBloc() : super(Initialization()) {
 on<AuthEvent>((event, emit) {
  emit(WaitingAuth());
  // Your logic
 }
}
  • Related