import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import '../../core/error_advice.dart'; import '../../core/error_reason.dart'; const errorNoticeDetailsKey = ValueKey('error-notice-details'); const errorNoticeCopyKey = ValueKey('error-notice-copy'); /// A failure as the operator should read it: a sentence saying what to do /// for the common kinds (not connected, server too old, permission, timeout) /// with the raw detail behind "Details" (selectable, with Copy); any other /// failure shows its own message. /// /// [error] is the exception or the message a controller kept. class ErrorNotice extends StatefulWidget { const ErrorNotice({ super.key, required this.error, this.textAlign = TextAlign.start, this.actions = const [], }); final Object error; /// Buttons for the failure (Retry), on one wrapping row with Details. final List actions; final TextAlign textAlign; @override State createState() => _ErrorNoticeState(); } class _ErrorNoticeState extends State { bool _open = false; @override Widget build(BuildContext context) { final theme = Theme.of(context); final color = theme.colorScheme.error; final advice = errorAdvice(widget.error); final error = widget.error; // Any other failure reads exactly as it was reported. final message = advice?.sentence ?? (error is String ? error : describeErrorReason(error, fallback: 'Something went wrong.')); final center = widget.textAlign == TextAlign.center; final text = Semantics( liveRegion: true, child: Text( message, textAlign: widget.textAlign, style: TextStyle(color: color), ), ); final alignment = center ? WrapAlignment.center : WrapAlignment.start; if (advice == null) { if (widget.actions.isEmpty) return text; return Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: center ? CrossAxisAlignment.center : CrossAxisAlignment.start, children: [ text, Wrap(alignment: alignment, children: widget.actions), ], ); } return Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: center ? CrossAxisAlignment.center : CrossAxisAlignment.start, children: [ text, Wrap( alignment: alignment, children: [ ...widget.actions, TextButton.icon( key: errorNoticeDetailsKey, onPressed: () => setState(() => _open = !_open), icon: Icon(_open ? Icons.expand_less : Icons.expand_more), label: Text(_open ? 'Hide details' : 'Details'), ), ], ), if (_open) Row( mainAxisSize: center ? MainAxisSize.min : MainAxisSize.max, crossAxisAlignment: CrossAxisAlignment.start, children: [ Flexible( child: SelectableText( advice.detail, style: theme.textTheme.bodySmall?.copyWith( color: theme.colorScheme.onSurfaceVariant, ), ), ), IconButton( key: errorNoticeCopyKey, tooltip: 'Copy details', icon: const Icon(Icons.copy, size: 18), onPressed: () => Clipboard.setData(ClipboardData(text: advice.detail)), ), ], ), ], ); } }