Sub topic 8
Triggering Errors on Purpose to Verify Both Handlers
Assume you know basic Dart syntax, async and await, Future, try/catch, and how to build a Flutter app with runApp. This chapter uses the two global handlers installed in main():
FlutterError.onErrorreceives errors reported by the Flutter framework.PlatformDispatcher.instance.onErrorreceives uncaught errors that escape the framework, including some failed asynchronous operations.
Testing both paths matters. A handler can compile correctly and still be attached to the wrong error channel.
Add a Small Test Page
Create a page with one button for each error type. The first button throws directly from a synchronous callback. Flutter invokes that callback as part of its framework event handling, so the error is sent to FlutterError.onError.
The second button is declared async. It waits briefly and then throws. The button callback returns a failed Future, but no code awaits or catches that future. The error can therefore reach PlatformDispatcher.instance.onError.
import 'package:flutter/material.dart';
class ErrorTestPage extends StatelessWidget {
const ErrorTestPage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Error handler test')),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton(
onPressed: () {
throw StateError('Synchronous button error');
},
child: const Text('Throw sync error'),
),
const SizedBox(height: 16),
ElevatedButton(
onPressed: () async {
await Future<void>.delayed(
const Duration(milliseconds: 100),
);
throw StateError('Asynchronous button error');
},
child: const Text('Throw async error'),
),
],
),
),
);
}
}Temporarily use ErrorTestPage as the home of your MaterialApp. Then run the app in debug mode and press each button separately.
void main() {
WidgetsFlutterBinding.ensureInitialized();
FlutterError.onError = (FlutterErrorDetails details) {
FlutterError.presentError(details);
debugPrint(
'FlutterError.onError: ${details.exceptionAsString()}',
);
};
PlatformDispatcher.instance.onError = (
Object error,
StackTrace stack,
) {
debugPrint('PlatformDispatcher.onError: $error');
debugPrint('$stack');
return true;
};
runApp(
const MaterialApp(
home: ErrorTestPage(),
),
);
}The first button should produce output from FlutterError.onError. The second should produce output from PlatformDispatcher.instance.onError. The exact console formatting depends on the platform and Flutter version, but the handler names in your messages identify the routing.
Check the Result Carefully
Use a real logging service only after confirming the local test. During development, keep FlutterError.presentError(details) in the framework handler. It preserves Flutter's normal console diagnostics, including useful context around the widget and framework operation.
The asynchronous handler returns a Boolean. Return true only when your application has handled or recorded the error. Returning false tells the platform that the error was not handled and may allow additional reporting or termination behavior.
Repeat the test in profile or release mode if your reporting setup behaves differently there. Debug mode can show error overlays and extra diagnostic output. Those visual responses do not prove that a production crash-reporting request succeeded.
Also test errors from code that you expect to catch yourself. For example, wrapping the asynchronous operation in try/catch prevents it from reaching the global handler:
Future<void> handledOperation() async {
try {
await Future<void>.delayed(const Duration(milliseconds: 100));
throw StateError('Handled locally');
} catch (error, stack) {
debugPrint('Caught locally: $error');
debugPrint('$stack');
}
}Global handlers are a last reporting boundary. They do not replace deliberate local error handling when the app can recover.
Exercise
Which handler should receive an exception thrown directly inside the synchronous onPressed callback, and which handler should receive an exception thrown after an awaited delay in an otherwise unobserved Future?
Show answer
The synchronous callback error should reach FlutterError.onError. The unobserved asynchronous failure should reach PlatformDispatcher.instance.onError.