Flutter: TextField onChanged handler inghiotte silenziosamente le eccezioni
Quando un'eccezione viene generata e non gestita in un TextField.onChangedgestore, non viene visualizzata nel Flutter.onErrorgestore globale, quindi viene ignorata silenziosamente. C'è un modo per gestire globalmente questi errori in modo che io sia almeno consapevole che vengono lanciati durante lo sviluppo?
Sembra essere catturato e convertito in un oggetto MethodChannel._handleAsMethodCall(), ma non capisco come venga gestito da lì.
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
},
),
),
),
);
}
}
Risposte
Il problema è che devi chiamare WidgetsFlutterBinding.ensureInitialized()prima di poter assegnare il tuo gestore di errori personalizzato: il seguente codice funziona per 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();
},
),
),
),
);
}
}
L'output della console durante la scrittura di '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
Potresti anche dare un'occhiata a Flutter: come implementare FlutterError.OnError correttamente e Flutter che cattura tutte le eccezioni non gestite poiché sembrano essere correlate al tuo problema.