Customized error screen in Flutter app

As errors could be fatal, error handling is one of the crucial areas for programmers, regardless of the application developed or programming languages used. It will be worse when an error occurs during run-time.

It can be as worst as Ariane 5 disaster notably one of the most expensive software failures in history. Nearly 37 seconds after initiation the rocket Ariane 5 flippped 90 degrees in wrong direction and less than 2 seconds later it is self destructed causing a damage of approximately $400 million.

So, errors and exceptions have to be handled gracefully.

But here we are not going to discuss various methods of error handling, but we are gonna see how to customize error screen in flutter.

In flutter, when an error ocurs hile building a widget the broken widget is replaced by ErrorWidget. That is- ErrorWidget.builder call back is used to build the widget. But by default, a red screen with error message is shown in debug mode [fig. (a)]; while a grey screen is shown in release mode [fig. (b)].

Error screen in debug mode.
(a) Error Screen in debug mode.
(b) Error screen in release mode.

HOW AND WHAT IN CUSTOMIZED ERROR BUILDER

In release mode, the user is unaware of what is happening. So it will be nice to show some error screen with custom description to make the user aware of the scenario. So, what we have to do is define the error widget builder in the MaterialApp widget in flutter main.

return MaterialApp(
title: 'Flutter Demo',
builder: (BuildContext context, Widget? widget) {
ErrorWidget.builder = (FlutterErrorDetails errorDetails) {
return CustomizedError(errorDetails: errorDetails);
// User defined CustomizedError extends statless widget.
};
return widget!;
},
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);

An objet of FlutterErrorDetails is passed to our CustomizedError widget, in the case we want to show the error details for debugging purposes.

Next part is to define the CustomizedError widget;

class CustomizedError extends StatelessWidget {
final FlutterErrorDetails errorDetails;

const CustomizedError({
Key? key,
required this.errorDetails,
}) : super(key: key);

@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(...),
/*
Customized text or image that has to be shown while runtime error occurs is defined in body.
errorDetails.summary.toString() can be used inside Text() widget to show the error in debug mode if necessary.
*/
);
}
}

Customized error screen [fig. ( c )] :-

Error widget customized
( c ) Customized error screen

Thanks for reading. If it worths please share.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store