Created
November 5, 2023 13:06
-
-
Save fredgrott/b941fafc2e4c3a609b6f2d3085114595 to your computer and use it in GitHub Desktop.
default app error catching in flutter sdk
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
Article is at https://open.substack.com/pub/fredgrott/p/better-app-exceptions-catching-than?r=26egx&utm_campaign=post&utm_medium=web