I've been using this library for a few days now, and I think it's excellent.
One thing that I'm not getting yet though, is how errors are supposed to be shown to the user.
I saw that there is an addError()
method in Bloc
s but that actually triggers the error to be thrown by the stream. What I'm looking for is a way to report something to the user.
Let's use the form example: how should I transport an error message to the UI if there was a problem submitting the form (for example: invalid data). Should I have a try/catch
in the bloc, and then an error
property on my State
class?
It would be great if there was an example (or if the existing examples would be updated) to contain common error handling too.
Hi @enyo 馃憢
Thanks for opening an issue and for the positive feedback! 馃檹
Regarding your question addError
is used to report an internal bloc error and it will trigger onError
in both the bloc as well as BlocObserver
.
Generally, blocs should catch any exceptions from their dependencies and convert them into a state for the UI to respond to:
@override
Stream<MyState> mapEventToState(MyEvent event) async* {
try {
final result = await _myRepository.fetch(...);
yield MyState.success(...);
} on Exception catch (error, stackTrace) {
yield MyState.failure(...);
}
}
An example of this can be seen in the flutter_weather example.
As far as validation errors, I would highly recommend checking out the flutter_form_validation example.
Hope that helps 馃憤
Thanks! I've looked at the form example and it handles everything but the part where the server could report an error (eg: the user tries to register but the email is already taken).
So am I right to assume that in that case, I should simply add an error message or code to the state that the UI can then display?
Yup, that's correct 馃憤