Skip to content

Instantly share code, notes, and snippets.

@fredgrott
Created November 5, 2023 13:06
Show Gist options
  • Save fredgrott/b941fafc2e4c3a609b6f2d3085114595 to your computer and use it in GitHub Desktop.
Save fredgrott/b941fafc2e4c3a609b6f2d3085114595 to your computer and use it in GitHub Desktop.
default app error catching in flutter sdk
import 'package:flutter/material.dart';
import 'dart:ui';
class MyErrorsHandler {
Future<void> initialize() async {
debugPrint('initialize');
// do some initialization
}
void onErrorDetails(FlutterErrorDetails details) {
debugPrint('onErrorDetails');
debugPrint(details.toString());
}
void onError(Object error, StackTrace stack) {
debugPrint('onError');
debugPrint(error.toString());
debugPrint(stack.toString());
}
}
// Since flutter 3.3 or so we no longer
// use separate zones to accomplish this as
// we are using platform dispatcher instead.
Future<void> main() async {
await myErrorsHandler.initialize();
FlutterError.onError = (details) {
FlutterError.presentError(details);
myErrorsHandler.onErrorDetails(details);
};
PlatformDispatcher.instance.onError = (error, stack) {
myErrorsHandler.onError(error, stack);
return true;
};
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
builder: (context, widget) {
Widget error = const Text('...rendering error...');
if (widget is Scaffold || widget is Navigator) {
error = Scaffold(body: Center(child: error));
}
ErrorWidget.builder = (errorDetails) => error;
if (widget != null) return widget;
throw ('widget is null');
},
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment