import 'dart:core';
import 'package:flutter/material.dart';
class AlertDialogApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
MaterialApp matApp = new MaterialApp(
home: ApplicationRootWidget(child: (WidgetWithAlert())),
);
return matApp;
}
}
void main() {
runApp(AlertDialogApp());
}
class WidgetWithAlert extends StatefulWidget {
WidgetWithAlert();
@override
WidgetWithAlertState createState() {
return new WidgetWithAlertState();
}
}
class WidgetWithAlertState extends State<WidgetWithAlert> {
@override
void initState() {
super.initState();
}
@override
void didChangeDependencies() {
if(ApplicationRootWidget.of(context).errorOccurred) {
// Error can be mitigated by substituting these two lines for the next line:
// WidgetsBinding.instance
// .addPostFrameCallback((_) => _showErrorAlert(context)); // Unclear how to retrieve the return value
_showErrorAlert(context);
}
super.didChangeDependencies();
}
Future<bool> _showErrorAlert(context) async {
Future<bool> result = showDialog(
context: context,
barrierDismissible: false,
builder: (BuildContext context) => AlertDialog(title: Text("An Error Occurred"),
content: Text("An unexpected error has occurred and we must restart the application. "
"Would you like to send a crash report before restarting, or just restart?"),
actions: [
FlatButton(
onPressed: () => Navigator.of(context).pop(false),
child: Text("Send Crash Report"),),
FlatButton(
onPressed: () => Navigator.of(context).pop(true),
child: Text("Just Restart"),),
]
)
);
return result;
}
@override
Widget build(BuildContext context) {
return Container(child:
Text("Hello World. All is well."));
}
}
class _InheritedApplicationRootWidgetState extends InheritedWidget {
final ApplicationRootWidgetState data;
const _InheritedApplicationRootWidgetState({
Key key,
@required this.data,
@required Widget child,
})
: assert(child != null),
super(key: key, child: child);
@override
bool updateShouldNotify(_InheritedApplicationRootWidgetState old) {
return true;
}
}
class ApplicationRootWidget extends StatefulWidget {
// You must pass through a child.
final Widget child;
ApplicationRootWidget({
@required this.child,
});
@override
ApplicationRootWidgetState createState() => ApplicationRootWidgetState();
static ApplicationRootWidgetState of(BuildContext context) {
return (context.inheritFromWidgetOfExactType(_InheritedApplicationRootWidgetState)
as _InheritedApplicationRootWidgetState).data;
}
}
class ApplicationRootWidgetState extends State<ApplicationRootWidget> {
bool errorOccurred = false;
@override
void initState() {
super.initState();
changeToError();
}
Future changeToError() async {
await Future.delayed(Duration(seconds: 2));
setState(() {
errorOccurred = true;
});
}
@override
Widget build(BuildContext context) {
return _InheritedApplicationRootWidgetState(data: this,
child: widget.child,
);
}
}