Handle build phase errors in Flutter
We often face errors while building widgets in flutter. Build phase errors can occur for various reasons.
When a widget throws while building, flutter shows an Error
screen with Red
background in debug mode. In release mode, it just presents an empty screen with grey background.
As a user, I would not like this.
Have you ever thought of showing a relevant error screen instead of this?
To replace the default error UI, pass a widget for ErrorWidget.builder
like this
ErrorWidget.builder
will be called whenever an error occurred while building a widget.
It’s a static builder and you can supply a value from anywhere.
A suitable place is the builder
function of MaterialApp
.
The builder
function will be called every time a widget is going to build. We can check here if the widget is building is a Screen
or not. If it is a Scaffold
or a Navigator
, we can assume it is a screen and thus can supply a suitable error screen.
Output:
Note: We should not write this much code inside the builder. It’s written here for demonstration purpose.
Thank you for reading! 😀 Let me know your feedback in comments.