felangel / bloc

A predictable state management library that helps implement the BLoC design pattern
https://bloclibrary.dev
MIT License
11.8k stars 3.39k forks source link

How to throw error to StreamBuilder.builder #2058

Closed xuanswe closed 3 years ago

xuanswe commented 3 years ago

I am using StreamBuilder to consume a Cubit. Asumme that I only want to use StreamBuilder for my widgets, don't want to use flutter_bloc package.

How can I throw error to snapshot.error in StreamBuilder.builder method?

I tried to use addError(), but my app just throws exception and I cannot handle the error inside StreamBuilder.builder method with snapshot.hasError.

xuanswe commented 3 years ago

If I wrap error inside my ErrorStateclass, I cannot handle the same error 2 times, because the cubit/bloc will ignore the same state. I want to retry the same thing after error and 99% I will get the same error and I need to handle it again.

felangel commented 3 years ago

Hi @nguyenxndaidev 👋 Thanks for opening an issue!

Out of curiosity, why do you wish to use StreamBuilder in favor of BlocBuilder?

How can I throw error to snapshot.error in StreamBuilder.builder method?

A bloc converts events into states and does not explicitly throw errors. You will need to yield some sort of an Error state from the bloc and handle it in the onData callback of the StreamBuilder.

If I wrap error inside my ErrorStateclass, I cannot handle the same error 2 times, because the cubit/bloc will ignore the same state.

If you always yield a new instance of the ErrorState and do not extend Equatable (or override hashCode and ==) then yield multiple ErrorState instances will emit multiple states.

Let me know if that helps 👍

xuanswe commented 3 years ago

Hi @felangel,

Thanks for your reply!

If you always yield a new instance of the ErrorState and do not extend Equatable (or override hashCode and ==) then yield multiple ErrorState instances will emit multiple states.

It means I need to change the State classes hierarchy, because normally I will use it at the root State class. Another workaround is to add smt random to props, ex. timestamp.

Out of curiosity, why do you wish to use StreamBuilder in favor of BlocBuilder?

I don't want to mix too many things from 3rd party libraries to my widget tree. If I want to change the architecture of my app, I want to minimize refactoring the widget tree. I also use other lib for dependency injection, so no need the help from flutter_bloc package.