【问题标题】:Flutter: TextField onChanged handler silently swallows exceptionsFlutter:TextField onChanged 处理程序默默吞下异常
【发布时间】:2021-02-04 18:29:31
【问题描述】:

当在TextField.onChanged 处理程序中抛出异常并且未处理它时,它不会冒泡到全局Flutter.onError 处理程序,因此它会被默默地遗漏。有没有办法全局处理这些错误,以便我至少知道它们在开发时被抛出?

它似乎在MethodChannel._handleAsMethodCall() 中被捕获并转换为一个对象,但我不明白它是如何从那里处理的。

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
            },
          ),
        ),
      ),
    );
  }
}

【问题讨论】:

    标签: flutter


    【解决方案1】:

    问题是您必须先调用WidgetsFlutterBinding.ensureInitialized(),然后才能分配自定义错误处理程序 - 以下代码适用于我:

    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(); 
                },
              ),
            ),
          ),
        );
      }
    }
    

    写入'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
    

    您可能还想查看Flutter: How to implement FlutterError.OnError correctlyFlutter catching all unhandled exceptions,因为它们似乎与您的问题有关。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-06-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多