Imagine I'm using a bloc to handle a network request. If the request fails, the way to handle the failure would be different depending on the platform. On my web app, I would like to redirect the user to an error page while on my IOS app I would like to show a dialog.
As bloc should only be used and shared to handle the business logic, and the error handling part has nothing to do with the business logic, we should ask the UI part to take care of the error handling.
The UI can send error callback to the bloc and the bloc will run it when an error happens. We can also handle the error in a platform-specific way by sending different callbacks in different platforms.
Then there come my two questions:
Is there a more appropriate way to do this?
How to send the callback to the bloc?
In flutter, we only have access to bloc after the initState
life cycle method(for we get bloc from builder context, which only comes after initState
). Then we can only send callback in the build method.
In this way, we will repetitively send callback to bloc every time rebuilding happens(these repetitions make no sense).
With react, such one-time initialization could be done in life cycles such as componentDidMount
.
In flutter how do we reach the goal of running these initialization only once?