Skip to content

Instantly share code, notes, and snippets.

@webstoreportal
Forked from felangel/main.dart
Created May 11, 2021 05:02
Show Gist options
  • Save webstoreportal/95d84478dfc7541e3544d97559816e0b to your computer and use it in GitHub Desktop.
Save webstoreportal/95d84478dfc7541e3544d97559816e0b to your computer and use it in GitHub Desktop.
Bloc Exception Handling
import 'dart:async';
import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
abstract class AuthenticationEvent extends Equatable {
AuthenticationEvent([List props = const []]) : super(props);
}
class LoginEvent extends AuthenticationEvent {
final String loginRequest;
LoginEvent(this.loginRequest) : super([loginRequest]);
@override
String toString() {
return 'LoginEvent{loginRequest: $loginRequest}';
}
}
abstract class AuthenticationState extends Equatable {
AuthenticationState([List props = const []]) : super(props);
}
class AuthenticationStateUnInitialized extends AuthenticationState {
@override
String toString() => 'AuthenticationStateUnInitialized';
}
class AuthenticationStateLoading extends AuthenticationState {
@override
String toString() => 'AuthenticationStateLoading';
}
class AuthenticationStateSuccess extends AuthenticationState {
String user;
AuthenticationStateSuccess(this.user) : super([user]);
@override
String toString() => 'AuthenticationStateSuccess{ user: $user }';
}
class AuthenticationStateError extends AuthenticationState {
final String error;
AuthenticationStateError(this.error) : super([error]);
@override
String toString() => 'AuthenticationStateError { error: $error }';
}
class AuthenticationBloc
extends Bloc<AuthenticationEvent, AuthenticationState> {
AuthenticationBloc();
@override
AuthenticationState get initialState => AuthenticationStateUnInitialized();
@override
Stream<AuthenticationState> mapEventToState(
AuthenticationState currentState,
AuthenticationEvent event,
) async* {
if (event is LoginEvent) {
yield AuthenticationStateLoading();
try {
final result = await _login(event.loginRequest);
yield AuthenticationStateSuccess(result);
} catch (e) {
yield AuthenticationStateError("error processing login request");
}
} else {
print("unknown");
}
}
Future<String> _login(dynamic request) async {
throw Exception();
}
@override
void onTransition(
Transition<AuthenticationEvent, AuthenticationState> transition,
) {
print(transition);
}
@override
void onError(Object error, StackTrace stacktrace) {
print('error in bloc $error $stacktrace');
}
}
void main() async {
AuthenticationBloc authBloc = AuthenticationBloc();
authBloc.state.listen((authState) {
print(authState);
});
authBloc.dispatch(LoginEvent('blah'));
await Future.delayed(Duration(seconds: 3));
authBloc.dispatch(LoginEvent('blah'));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment