package_exception_handler 0.3.0 package_exception_handler: ^0.3.0 copied to clipboard
Flutter package for exception handling within custom packages.
// Copyright (c) 2019, the EOMarch project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:package_exception_handler/package_exception_handler.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
final navigatorKey = GlobalKey<NavigatorState>();
final scaffoldKey = GlobalKey<ScaffoldState>();
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> with ErrorStream {
var stackTrace = '';
@override
void initState() {
initErrorStream(); // To be sure that after disposing Stream will be initialized again
error.listen((data) {
widget.scaffoldKey.currentState.showSnackBar(SnackBar(
duration: const Duration(seconds: 3),
content: Text(data.currentError.toString()), // Gets current Error or Exception
action: SnackBarAction(
label: 'Stack Trace',
onPressed: () => setState(() => stackTrace = data.stackTrace
?.toString()), // Gets stack trace, if it have been provided
),
));
});
super.initState();
}
@override
void dispose() {
disposeErrorStream(); // Need to dispose error to prevent memory leaks
super.dispose();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
navigatorKey: widget.navigatorKey,
home: Scaffold(
key: widget.scaffoldKey,
appBar: AppBar(
title: const Text('Pkg Exception Handler Example App'),
),
body: Center(
child: FractionallySizedBox(
widthFactor: 0.75,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
RaisedButton(
onPressed: () {
// Handles sync error if retutn type is void or it doesn't matter
handleError(() {
// do stuff that might fail
throw AssertionError();
});
},
child: Text('Generate Error'),
),
SizedBox(height: 25),
RaisedButton(
onPressed: () {
// Handles async error if retutn type is void or it doesn't matter
handleErrorAsync(Future.delayed(const Duration(seconds: 2))
.whenComplete(() => throw FormatException()));
},
child: Text('Generate Async Error'),
),
SizedBox(height: 25),
RaisedButton(
onPressed: () {
// Handle error on your own using recordError method within catch statement
try {
// do stuff that might fail
throw UnsupportedError('test error');
} catch (e, stackTrace) {
recordError(e,
stackTrace); // Add Error or Exception (with StackTrace) to stream
return false;
}
},
child: Text('Generate Error with Raw Handling'),
),
SizedBox(height: 50),
InkResponse(
onTap: () => setState(() => stackTrace = ''),
child: Text(stackTrace),
),
],
),
),
),
),
);
}
}