'Flutter FutureBuilder exceptions: add default behaviour
In my app I use FutureBuilder
extensively and I would like a generic behaviour when one of them fails. I am trying this setup
WidgetsFlutterBinding.ensureInitialized(); //imp line need to be added first
FlutterError.onError = (FlutterErrorDetails details) async {
print("*** CAUGHT FROM FRAMEWORK ***");
await FirebaseCrashlytics.instance.recordFlutterError(details);
};
runZonedGuarded(() {
runApp(new MaterialApp(
debugShowCheckedModeBanner: false,
home: new Container(
decoration: new BoxDecoration(color: Colors.grey.shade400),
child: Center(child: new LaunchWidget()))
),
);
}, (Object error, StackTrace stackTrace) {
print("**** ZONED EXCEPTION ****");
FirebaseCrashlytics.instance.recordError(error, stackTrace);
});
With this setup any failing FutureBuilder
won't go in any of the two error handlers.
The only way to do something is to use
FutureBuilder<void>(
future: failingFuture(context),
builder: (context, snapshot) => (snapshot.hasError) handle() : doSomething()
is there any less verbose way to handle this?
Solution 1:[1]
I've ended up doing this:
import 'package:flutter/material.dart';
/// Wrap builder to report errors
class FutureBuilder2<T> extends FutureBuilder<T> {
FutureBuilder2({
Key? key,
Future<T>? future,
T? initialData,
required AsyncWidgetBuilder<T> builder,
}) : super(
key: key,
future: future,
initialData: initialData,
builder: (BuildContext context, AsyncSnapshot<T> snapshot) {
if (snapshot.hasError) {
FlutterError.reportError(FlutterErrorDetails(
exception: snapshot.error!, stack: snapshot.stackTrace));
}
return builder(context, snapshot);
});
}
You'll have to remember to use FutureBuilder2, but it seems to be the best that I could come up with. Also, properly name it better ;)
If anybody knows of any drawbacks when doing this, please let me know
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |