Flutter:如何正确实现FlutterError.OnError

Flutter: How to implement FlutterError.OnError correctly

谁能告诉我如何在小部件测试期间实现覆盖 flutter 错误,这样我就可以检查自己的自定义错误。

我在网上看到了提到这个的片段,但我的所有实现都失败了

void main() {

  testWidgets('throws an error when scanning unknown term types', (WidgetTester tester) async {
    await tester.pumpWidget(injectTestWidget(new ItemScanScreen()));

    await tester.enterText(find.byKey(new Key('term')), '');
    await tester.tap(find.byIcon(Icons.send));
    await tester.pump();

    expect(
      tester.takeException(),
      isInstanceOf<UnrecognizedTermException>(),
      reason: 'should have thrown an UnrecognizedTermException error but didn\'t',
    );
  });
}

上面的代码失败并显示以下消息,即使它看起来确实如此 'caught' 我的错误:

The following UnrecognizedTermException was thrown running a test:
Instance of 'UnrecognizedTermException'
...

我读到您可以执行类似于下面的代码片段的操作,但没有看到 how/where 来实现它:

final errorHandled = expectAsync0((){});

FlutterError.onError = (errorDetails) {
  // handle error
  errorHandled();
});

这是为测试而设计的。我在 try/catch 中切换到包装逻辑,然后在 "error message text" 当前概念上切换到 运行 expect() 。例如:

try {
   throw new UnrecognizedTermException();
 } catch (e) {
   setState(() => _status = e.errMsg());
}

// then in my test
expect(find.text('Could not determine the type of item you scanned'), findsOneWidget);

我在生产中使用下面的代码将错误记录到服务器。

main.dart:

import 'dart:async';
import 'package:flutter/material.dart';
import 'logging.dart';

void main() async {
  FlutterError.onError = (FlutterErrorDetails details) async {
    new ErrorLogger().logError(details);
  };
  runZoned<Future<void>>(() async {
    // Your App Here
    runApp(MainApp());
  }, onError: (error, stackTrace) {
    new ErrorLogger().log(error, stackTrace);
  });
}

logging.dart:

class ErrorLogger {

  void logError(FlutterErrorDetails details) async {
    //FlutterError.dumpErrorToConsole(details);
    _sendToServer(details.exceptionAsString(), details.stack.toString());
  }

  void log(Object data, StackTrace stackTrace) async {  
      // print(data);
      // print(stackTrace);
    _sendToServer(data.toString(), stackTrace.toString());
  }

  void _sendToServer(String a, String b) async {
    // Implementation here
  }
}