2

When an exception is thrown and unhandled in a TextField.onChanged handler it doesn't bubble up to the global Flutter.onError handler so it's silently missed. Is there a way to globally handle these errors so that I'm at least aware that they're thrown when developing?

It appears to be caught and converted into an object in MethodChannel._handleAsMethodCall(), but I don't understand how it's handled from there.

main() {
  runApp(Test());
}

class Test extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Center(
          child: TextField(
            decoration: InputDecoration(
              labelText: "Input",
            ),
            onChanged: (input) {
              throw Exception(); // <-------- swallowed by framework
            },
          ),
        ),
      ),
    );
  }
}
geg
  • 4,399
  • 4
  • 34
  • 35

1 Answers1

2

The problem is that you have to call WidgetsFlutterBinding.ensureInitialized() before you can assign your custom error handler - the following code works for me:

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
void main() {
  WidgetsFlutterBinding.ensureInitialized(); // <- this needs to happen before assigning your error handler
  FlutterError.onError = (FlutterErrorDetails details) => print('custom error handling');
  runApp(Test());
}

class Test extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Center(
          child: TextField(
            decoration: InputDecoration(
              labelText: "Input",
            ),
            onChanged: (input) {
              print(input);
              throw Exception(); 
            },
          ),
        ),
      ),
    );
  }
}

The console output when writing 'uiae':

Performing hot restart...
Syncing files to device Chrome...
Restarted application in 434ms.
u
custom error handling
ui
custom error handling
uia
custom error handling
uiae
custom error handling

You may also want to take a look at Flutter: How to implement FlutterError.OnError correctly and Flutter catching all unhandled exceptions as they seem to be related to your problem.

Damian K. Bast
  • 1,074
  • 7
  • 18