diff --git a/packages/flutter/lib/src/animation/animations.dart b/packages/flutter/lib/src/animation/animations.dart index 4f0dc26236..7d8ee283e9 100644 --- a/packages/flutter/lib/src/animation/animations.dart +++ b/packages/flutter/lib/src/animation/animations.dart @@ -439,12 +439,14 @@ class CurvedAnimation extends Animation with AnimationWithParentMixin[ + ErrorSummary('Invalid curve endpoint at $t.'), + ErrorDescription( + 'Curves must map 0.0 to near zero and 1.0 to near one but ' + '${activeCurve.runtimeType} mapped $t to $transformedValue, which ' + 'is near $roundedTransformedValue.' + ) + ]); } return true; }()); diff --git a/packages/flutter/lib/src/cupertino/tab_view.dart b/packages/flutter/lib/src/cupertino/tab_view.dart index 1984c9e963..f217e214a5 100644 --- a/packages/flutter/lib/src/cupertino/tab_view.dart +++ b/packages/flutter/lib/src/cupertino/tab_view.dart @@ -192,29 +192,33 @@ class _CupertinoTabViewState extends State { Route _onUnknownRoute(RouteSettings settings) { assert(() { if (widget.onUnknownRoute == null) { - throw FlutterError( - 'Could not find a generator for route $settings in the $runtimeType.\n' - 'Generators for routes are searched for in the following order:\n' - ' 1. For the "/" route, the "builder" property, if non-null, is used.\n' - ' 2. Otherwise, the "routes" table is used, if it has an entry for ' - 'the route.\n' - ' 3. Otherwise, onGenerateRoute is called. It should return a ' - 'non-null value for any valid route not handled by "builder" and "routes".\n' - ' 4. Finally if all else fails onUnknownRoute is called.\n' - 'Unfortunately, onUnknownRoute was not set.' - ); + throw FlutterError.fromParts([ + ErrorSummary('Could not find a generator for route $settings in the $runtimeType.'), + ErrorDescription( + 'Generators for routes are searched for in the following order:\n' + ' 1. For the "/" route, the "builder" property, if non-null, is used.\n' + ' 2. Otherwise, the "routes" table is used, if it has an entry for ' + 'the route.\n' + ' 3. Otherwise, onGenerateRoute is called. It should return a ' + 'non-null value for any valid route not handled by "builder" and "routes".\n' + ' 4. Finally if all else fails onUnknownRoute is called.\n' + 'Unfortunately, onUnknownRoute was not set.' + ) + ]); } return true; }()); final Route result = widget.onUnknownRoute(settings); assert(() { if (result == null) { - throw FlutterError( - 'The onUnknownRoute callback returned null.\n' - 'When the $runtimeType requested the route $settings from its ' - 'onUnknownRoute callback, the callback returned null. Such callbacks ' - 'must never return null.' - ); + throw FlutterError.fromParts([ + ErrorSummary('The onUnknownRoute callback returned null.'), + ErrorDescription( + 'When the $runtimeType requested the route $settings from its ' + 'onUnknownRoute callback, the callback returned null. Such callbacks ' + 'must never return null.' + ) + ]); } return true; }()); diff --git a/packages/flutter/lib/src/foundation/change_notifier.dart b/packages/flutter/lib/src/foundation/change_notifier.dart index 1e51dd1560..51732dcaa6 100644 --- a/packages/flutter/lib/src/foundation/change_notifier.dart +++ b/packages/flutter/lib/src/foundation/change_notifier.dart @@ -102,10 +102,10 @@ class ChangeNotifier implements Listenable { bool _debugAssertNotDisposed() { assert(() { if (_listeners == null) { - throw FlutterError( - 'A $runtimeType was used after being disposed.\n' - 'Once you have called dispose() on a $runtimeType, it can no longer be used.' - ); + throw FlutterError.fromParts([ + ErrorSummary('A $runtimeType was used after being disposed.'), + ErrorDescription('Once you have called dispose() on a $runtimeType, it can no longer be used.') + ]); } return true; }()); diff --git a/packages/flutter/lib/src/material/debug.dart b/packages/flutter/lib/src/material/debug.dart index 34b9173824..beeb7ecc6f 100644 --- a/packages/flutter/lib/src/material/debug.dart +++ b/packages/flutter/lib/src/material/debug.dart @@ -2,6 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +import 'package:flutter/foundation.dart'; import 'package:flutter/widgets.dart'; import 'material.dart'; @@ -24,45 +25,26 @@ import 'scaffold.dart' show Scaffold; bool debugCheckHasMaterial(BuildContext context) { assert(() { if (context.widget is! Material && context.ancestorWidgetOfExactType(Material) == null) { - final StringBuffer message = StringBuffer(); - message.writeln('No Material widget found.'); - message.writeln( - '${context.widget.runtimeType} widgets require a Material ' - 'widget ancestor.' + throw FlutterError.fromParts([ + ErrorSummary('No Material widget found.'), + ErrorDescription( + '${context.widget.runtimeType} widgets require a Material ' + 'widget ancestor.\n' + 'In material design, most widgets are conceptually "printed" on ' + 'a sheet of material. In Flutter\'s material library, that ' + 'material is represented by the Material widget. It is the ' + 'Material widget that renders ink splashes, for instance. ' + 'Because of this, many material library widgets require that ' + 'there be a Material widget in the tree above them.' + ), + ErrorHint( + 'To introduce a Material widget, you can either directly ' + 'include one, or use a widget that contains Material itself, ' + 'such as a Card, Dialog, Drawer, or Scaffold.', + ), + ...context.describeMissingAncestor(expectedAncestorType: Material) + ] ); - message.writeln( - 'In material design, most widgets are conceptually "printed" on ' - 'a sheet of material. In Flutter\'s material library, that ' - 'material is represented by the Material widget. It is the ' - 'Material widget that renders ink splashes, for instance. ' - 'Because of this, many material library widgets require that ' - 'there be a Material widget in the tree above them.' - ); - message.writeln( - 'To introduce a Material widget, you can either directly ' - 'include one, or use a widget that contains Material itself, ' - 'such as a Card, Dialog, Drawer, or Scaffold.' - ); - message.writeln( - 'The specific widget that could not find a Material ancestor was:' - ); - message.writeln(' ${context.widget}'); - final List ancestors = []; - context.visitAncestorElements((Element element) { - ancestors.add(element.widget); - return true; - }); - if (ancestors.isNotEmpty) { - message.write('The ancestors of this widget were:'); - for (Widget ancestor in ancestors) - message.write('\n $ancestor'); - } else { - message.writeln( - 'This widget is the root of the tree, so it has no ' - 'ancestors, let alone a "Material" ancestor.' - ); - } - throw FlutterError(message.toString()); } return true; }()); @@ -87,42 +69,24 @@ bool debugCheckHasMaterial(BuildContext context) { bool debugCheckHasMaterialLocalizations(BuildContext context) { assert(() { if (Localizations.of(context, MaterialLocalizations) == null) { - final StringBuffer message = StringBuffer(); - message.writeln('No MaterialLocalizations found.'); - message.writeln( - '${context.widget.runtimeType} widgets require MaterialLocalizations ' - 'to be provided by a Localizations widget ancestor.' - ); - message.writeln( - 'Localizations are used to generate many different messages, labels,' - 'and abbreviations which are used by the material library. ' - ); - message.writeln( - 'To introduce a MaterialLocalizations, either use a ' - ' MaterialApp at the root of your application to include them ' - 'automatically, or add a Localization widget with a ' - 'MaterialLocalizations delegate.' - ); - message.writeln( - 'The specific widget that could not find a MaterialLocalizations ancestor was:' - ); - message.writeln(' ${context.widget}'); - final List ancestors = []; - context.visitAncestorElements((Element element) { - ancestors.add(element.widget); - return true; - }); - if (ancestors.isNotEmpty) { - message.write('The ancestors of this widget were:'); - for (Widget ancestor in ancestors) - message.write('\n $ancestor'); - } else { - message.writeln( - 'This widget is the root of the tree, so it has no ' - 'ancestors, let alone a "Localizations" ancestor.' - ); - } - throw FlutterError(message.toString()); + throw FlutterError.fromParts([ + ErrorSummary('No MaterialLocalizations found.'), + ErrorDescription( + '${context.widget.runtimeType} widgets require MaterialLocalizations ' + 'to be provided by a Localizations widget ancestor.' + ), + ErrorDescription( + 'Localizations are used to generate many different messages, labels,' + 'and abbreviations which are used by the material library.' + ), + ErrorHint( + 'To introduce a MaterialLocalizations, either use a ' + 'MaterialApp at the root of your application to include them ' + 'automatically, or add a Localization widget with a ' + 'MaterialLocalizations delegate.' + ), + ...context.describeMissingAncestor(expectedAncestorType: MaterialLocalizations) + ]); } return true; }()); @@ -145,17 +109,15 @@ bool debugCheckHasMaterialLocalizations(BuildContext context) { bool debugCheckHasScaffold(BuildContext context) { assert(() { if (context.widget is! Scaffold && context.ancestorWidgetOfExactType(Scaffold) == null) { - final Element element = context; - throw FlutterError( - 'No Scaffold widget found.\n' - '${context.widget.runtimeType} widgets require a Scaffold widget ancestor.\n' - 'The Specific widget that could not find a Scaffold ancestor was:\n' - ' ${context.widget}\n' - 'The ownership chain for the affected widget is:\n' - ' ${element.debugGetCreatorChain(10)}\n' + throw FlutterError.fromParts([ + ErrorSummary('No Scaffold widget found.'), + ErrorDescription('${context.widget.runtimeType} widgets require a Scaffold widget ancestor.'), + ...context.describeMissingAncestor(expectedAncestorType: Scaffold), + ErrorHint( 'Typically, the Scaffold widget is introduced by the MaterialApp or ' 'WidgetsApp widget at the top of your application widget tree.' - ); + ) + ]); } return true; }()); diff --git a/packages/flutter/lib/src/material/page.dart b/packages/flutter/lib/src/material/page.dart index d76af283a2..bea922037f 100644 --- a/packages/flutter/lib/src/material/page.dart +++ b/packages/flutter/lib/src/material/page.dart @@ -87,10 +87,10 @@ class MaterialPageRoute extends PageRoute { final Widget result = builder(context); assert(() { if (result == null) { - throw FlutterError( - 'The builder for route "${settings.name}" returned null.\n' - 'Route builders must never return null.' - ); + throw FlutterError.fromParts([ + ErrorSummary('The builder for route "${settings.name}" returned null.'), + ErrorDescription('Route builders must never return null.') + ]); } return true; }()); diff --git a/packages/flutter/lib/src/material/scaffold.dart b/packages/flutter/lib/src/material/scaffold.dart index a167460eaa..f3292fe2ab 100644 --- a/packages/flutter/lib/src/material/scaffold.dart +++ b/packages/flutter/lib/src/material/scaffold.dart @@ -1310,25 +1310,32 @@ class Scaffold extends StatefulWidget { final ScaffoldState result = context.ancestorStateOfType(const TypeMatcher()); if (nullOk || result != null) return result; - throw FlutterError( - 'Scaffold.of() called with a context that does not contain a Scaffold.\n' - 'No Scaffold ancestor could be found starting from the context that was passed to Scaffold.of(). ' - 'This usually happens when the context provided is from the same StatefulWidget as that ' - 'whose build function actually creates the Scaffold widget being sought.\n' - 'There are several ways to avoid this problem. The simplest is to use a Builder to get a ' - 'context that is "under" the Scaffold. For an example of this, please see the ' - 'documentation for Scaffold.of():\n' - ' https://api.flutter.dev/flutter/material/Scaffold/of.html\n' - 'A more efficient solution is to split your build function into several widgets. This ' - 'introduces a new context from which you can obtain the Scaffold. In this solution, ' - 'you would have an outer widget that creates the Scaffold populated by instances of ' - 'your new inner widgets, and then in these inner widgets you would use Scaffold.of().\n' - 'A less elegant but more expedient solution is assign a GlobalKey to the Scaffold, ' - 'then use the key.currentState property to obtain the ScaffoldState rather than ' - 'using the Scaffold.of() function.\n' - 'The context used was:\n' - ' $context' - ); + throw FlutterError.fromParts([ + ErrorSummary( + 'Scaffold.of() called with a context that does not contain a Scaffold.' + ), + ErrorDescription( + 'No Scaffold ancestor could be found starting from the context that was passed to Scaffold.of(). ' + 'This usually happens when the context provided is from the same StatefulWidget as that ' + 'whose build function actually creates the Scaffold widget being sought.' + ), + ErrorHint( + 'There are several ways to avoid this problem. The simplest is to use a Builder to get a ' + 'context that is "under" the Scaffold. For an example of this, please see the ' + 'documentation for Scaffold.of():\n' + ' https://api.flutter.dev/flutter/material/Scaffold/of.html' + ), + ErrorHint( + 'A more efficient solution is to split your build function into several widgets. This ' + 'introduces a new context from which you can obtain the Scaffold. In this solution, ' + 'you would have an outer widget that creates the Scaffold populated by instances of ' + 'your new inner widgets, and then in these inner widgets you would use Scaffold.of().\n' + 'A less elegant but more expedient solution is assign a GlobalKey to the Scaffold, ' + 'then use the key.currentState property to obtain the ScaffoldState rather than ' + 'using the Scaffold.of() function.' + ), + context.describeElement('The context used was') + ]); } /// Returns a [ValueListenable] for the [ScaffoldGeometry] for the closest @@ -1354,22 +1361,28 @@ class Scaffold extends StatefulWidget { static ValueListenable geometryOf(BuildContext context) { final _ScaffoldScope scaffoldScope = context.inheritFromWidgetOfExactType(_ScaffoldScope); if (scaffoldScope == null) - throw FlutterError( - 'Scaffold.geometryOf() called with a context that does not contain a Scaffold.\n' - 'This usually happens when the context provided is from the same StatefulWidget as that ' - 'whose build function actually creates the Scaffold widget being sought.\n' - 'There are several ways to avoid this problem. The simplest is to use a Builder to get a ' - 'context that is "under" the Scaffold. For an example of this, please see the ' - 'documentation for Scaffold.of():\n' - ' https://api.flutter.dev/flutter/material/Scaffold/of.html\n' - 'A more efficient solution is to split your build function into several widgets. This ' - 'introduces a new context from which you can obtain the Scaffold. In this solution, ' - 'you would have an outer widget that creates the Scaffold populated by instances of ' - 'your new inner widgets, and then in these inner widgets you would use Scaffold.geometryOf().\n' - 'The context used was:\n' - ' $context' - ); - + throw FlutterError.fromParts([ + ErrorSummary( + 'Scaffold.geometryOf() called with a context that does not contain a Scaffold.' + ), + ErrorDescription( + 'This usually happens when the context provided is from the same StatefulWidget as that ' + 'whose build function actually creates the Scaffold widget being sought.' + ), + ErrorHint( + 'There are several ways to avoid this problem. The simplest is to use a Builder to get a ' + 'context that is "under" the Scaffold. For an example of this, please see the ' + 'documentation for Scaffold.of():\n' + ' https://api.flutter.dev/flutter/material/Scaffold/of.html' + ), + ErrorHint( + 'A more efficient solution is to split your build function into several widgets. This ' + 'introduces a new context from which you can obtain the Scaffold. In this solution, ' + 'you would have an outer widget that creates the Scaffold populated by instances of ' + 'your new inner widgets, and then in these inner widgets you would use Scaffold.geometryOf().', + ), + context.describeElement('The context used was') + ]); return scaffoldScope.geometryNotifier; } @@ -1679,9 +1692,9 @@ class ScaffoldState extends State with TickerProviderStateMixin { assert(() { if (widget.bottomSheet != null && isPersistent && _currentBottomSheet != null) { throw FlutterError( - 'Scaffold.bottomSheet cannot be specified while a bottom sheet displayed ' - 'with showBottomSheet() is still visible.\n Rebuild the Scaffold with a null ' - 'bottomSheet before calling showBottomSheet().' + 'Scaffold.bottomSheet cannot be specified while a bottom sheet' + 'displayed with showBottomSheet() is still visible.\n' + 'Rebuild the Scaffold with a null bottomSheet before calling showBottomSheet().' ); } return true; @@ -1818,9 +1831,9 @@ class ScaffoldState extends State with TickerProviderStateMixin { assert(() { if (widget.bottomSheet != null) { throw FlutterError( - 'Scaffold.bottomSheet cannot be specified while a bottom sheet displayed ' - 'with showBottomSheet() is still visible.\n Rebuild the Scaffold with a null ' - 'bottomSheet before calling showBottomSheet().' + 'Scaffold.bottomSheet cannot be specified while a bottom sheet' + 'displayed with showBottomSheet() is still visible.\n' + 'Rebuild the Scaffold with a null bottomSheet before calling showBottomSheet().' ); } return true; @@ -1952,12 +1965,17 @@ class ScaffoldState extends State with TickerProviderStateMixin { if (widget.bottomSheet != oldWidget.bottomSheet) { assert(() { if (widget.bottomSheet != null && _currentBottomSheet?._isLocalHistoryEntry == true) { - throw FlutterError( - 'Scaffold.bottomSheet cannot be specified while a bottom sheet displayed ' - 'with showBottomSheet() is still visible.\n Use the PersistentBottomSheetController ' - 'returned by showBottomSheet() to close the old bottom sheet before creating ' - 'a Scaffold with a (non null) bottomSheet.' - ); + throw FlutterError.fromParts([ + ErrorSummary( + 'Scaffold.bottomSheet cannot be specified while a bottom sheet displayed ' + 'with showBottomSheet() is still visible.' + ), + ErrorHint( + 'Use the PersistentBottomSheetController ' + 'returned by showBottomSheet() to close the old bottom sheet before creating ' + 'a Scaffold with a (non null) bottomSheet.' + ), + ]); } return true; }()); diff --git a/packages/flutter/lib/src/material/stepper.dart b/packages/flutter/lib/src/material/stepper.dart index e0f7aa90b5..653de0914e 100644 --- a/packages/flutter/lib/src/material/stepper.dart +++ b/packages/flutter/lib/src/material/stepper.dart @@ -672,8 +672,9 @@ class _StepperState extends State with TickerProviderStateMixin { assert(() { if (context.ancestorWidgetOfExactType(Stepper) != null) throw FlutterError( - 'Steppers must not be nested. The material specification advises ' - 'that one should avoid embedding steppers within steppers. ' + 'Steppers must not be nested.\n' + 'The material specification advises that one should avoid embedding ' + 'steppers within steppers. ' 'https://material.io/archive/guidelines/components/steppers.html#steppers-usage' ); return true; diff --git a/packages/flutter/lib/src/painting/box_border.dart b/packages/flutter/lib/src/painting/box_border.dart index 5d6f432ca3..56ca8fa536 100644 --- a/packages/flutter/lib/src/painting/box_border.dart +++ b/packages/flutter/lib/src/painting/box_border.dart @@ -152,14 +152,16 @@ abstract class BoxBorder extends ShapeBorder { bottom: BorderSide.lerp(a.bottom, b.bottom, t), ); } - throw FlutterError( - 'BoxBorder.lerp can only interpolate Border and BorderDirectional classes.\n' - 'BoxBorder.lerp() was called with two objects of type ${a.runtimeType} and ${b.runtimeType}:\n' - ' $a\n' - ' $b\n' - 'However, only Border and BorderDirectional classes are supported by this method. ' - 'For a more general interpolation method, consider using ShapeBorder.lerp instead.' - ); + throw FlutterError.fromParts([ + ErrorSummary('BoxBorder.lerp can only interpolate Border and BorderDirectional classes.'), + ErrorDescription( + 'BoxBorder.lerp() was called with two objects of type ${a.runtimeType} and ${b.runtimeType}:\n' + ' $a\n' + ' $b\n' + 'However, only Border and BorderDirectional classes are supported by this method.' + ), + ErrorHint('For a more general interpolation method, consider using ShapeBorder.lerp instead.'), + ]); } @override diff --git a/packages/flutter/lib/src/painting/decoration_image.dart b/packages/flutter/lib/src/painting/decoration_image.dart index 2099c6126f..2853721400 100644 --- a/packages/flutter/lib/src/painting/decoration_image.dart +++ b/packages/flutter/lib/src/painting/decoration_image.dart @@ -221,15 +221,15 @@ class DecorationImagePainter { // We check this first so that the assert will fire immediately, not just // when the image is ready. if (configuration.textDirection == null) { - throw FlutterError( - 'ImageDecoration.matchTextDirection can only be used when a TextDirection is available.\n' - 'When DecorationImagePainter.paint() was called, there was no text direction provided ' - 'in the ImageConfiguration object to match.\n' - 'The DecorationImage was:\n' - ' $_details\n' - 'The ImageConfiguration was:\n' - ' $configuration' - ); + throw FlutterError.fromParts([ + ErrorSummary('ImageDecoration.matchTextDirection can only be used when a TextDirection is available.'), + ErrorDescription( + 'When DecorationImagePainter.paint() was called, there was no text direction provided ' + 'in the ImageConfiguration object to match.' + ), + DiagnosticsProperty('The DecorationImage was', _details, style: DiagnosticsTreeStyle.errorProperty), + DiagnosticsProperty('The ImageConfiguration was', configuration, style: DiagnosticsTreeStyle.errorProperty), + ]); } return true; }()); diff --git a/packages/flutter/lib/src/painting/text_span.dart b/packages/flutter/lib/src/painting/text_span.dart index 6e09fa7bba..f1c2aeb866 100644 --- a/packages/flutter/lib/src/painting/text_span.dart +++ b/packages/flutter/lib/src/painting/text_span.dart @@ -362,12 +362,15 @@ class TextSpan extends InlineSpan { assert(() { if (children != null) { for (InlineSpan child in children) { - assert(child != null, - 'TextSpan contains a null child.\n...' - 'A TextSpan object with a non-null child list should not have any nulls in its child list.\n' - 'The full text in question was:\n' - '${toStringDeep(prefixLineOne: ' ')}' - ); + if (child == null) { + throw FlutterError.fromParts([ + ErrorSummary('TextSpan contains a null child.'), + ErrorDescription( + 'A TextSpan object with a non-null child list should not have any nulls in its child list.'), + toDiagnosticsNode(name: 'The full text in question was', + style: DiagnosticsTreeStyle.errorProperty), + ]); + } assert(child.debugAssertIsValid()); } } diff --git a/packages/flutter/lib/src/rendering/custom_layout.dart b/packages/flutter/lib/src/rendering/custom_layout.dart index cd6c69e7fe..c6e763edcd 100644 --- a/packages/flutter/lib/src/rendering/custom_layout.dart +++ b/packages/flutter/lib/src/rendering/custom_layout.dart @@ -134,27 +134,29 @@ abstract class MultiChildLayoutDelegate { final RenderBox child = _idToChild[childId]; assert(() { if (child == null) { - throw FlutterError( - 'The $this custom multichild layout delegate tried to lay out a non-existent child.\n' - 'There is no child with the id "$childId".' - ); + throw FlutterError.fromParts([ + ErrorSummary('The $this custom multichild layout delegate tried to lay out a non-existent child.'), + ErrorDescription('There is no child with the id "$childId".') + ]); } if (!_debugChildrenNeedingLayout.remove(child)) { - throw FlutterError( - 'The $this custom multichild layout delegate tried to lay out the child with id "$childId" more than once.\n' - 'Each child must be laid out exactly once.' - ); + throw FlutterError.fromParts([ + ErrorSummary('The $this custom multichild layout delegate tried to lay out the child with id "$childId" more than once.'), + ErrorDescription('Each child must be laid out exactly once.') + ]); } try { assert(constraints.debugAssertIsValid(isAppliedConstraint: true)); } on AssertionError catch (exception) { - throw FlutterError( - 'The $this custom multichild layout delegate provided invalid box constraints for the child with id "$childId".\n' - '$exception\n' - 'The minimum width and height must be greater than or equal to zero.\n' - 'The maximum width must be greater than or equal to the minimum width.\n' - 'The maximum height must be greater than or equal to the minimum height.' - ); + throw FlutterError.fromParts([ + ErrorSummary('The $this custom multichild layout delegate provided invalid box constraints for the child with id "$childId".'), + DiagnosticsProperty('Exception', exception, showName: false), + ErrorDescription( + 'The minimum width and height must be greater than or equal to zero.\n' + 'The maximum width must be greater than or equal to the minimum width.\n' + 'The maximum height must be greater than or equal to the minimum height.' + ) + ]); } return true; }()); @@ -172,15 +174,15 @@ abstract class MultiChildLayoutDelegate { final RenderBox child = _idToChild[childId]; assert(() { if (child == null) { - throw FlutterError( - 'The $this custom multichild layout delegate tried to position out a non-existent child:\n' - 'There is no child with the id "$childId".' - ); + throw FlutterError.fromParts([ + ErrorSummary('The $this custom multichild layout delegate tried to position out a non-existent child:'), + ErrorDescription('There is no child with the id "$childId".') + ]); } if (offset == null) { - throw FlutterError( - 'The $this custom multichild layout delegate provided a null position for the child with id "$childId".' - ); + throw FlutterError.fromParts([ + ErrorSummary('The $this custom multichild layout delegate provided a null position for the child with id "$childId".') + ]); } return true; }()); @@ -188,9 +190,9 @@ abstract class MultiChildLayoutDelegate { childParentData.offset = offset; } - String _debugDescribeChild(RenderBox child) { + DiagnosticsNode _debugDescribeChild(RenderBox child) { final MultiChildLayoutParentData childParentData = child.parentData; - return '${childParentData.id}: $child'; + return DiagnosticsProperty('${childParentData.id}', child); } void _callPerformLayout(Size size, RenderBox firstChild) { @@ -213,11 +215,10 @@ abstract class MultiChildLayoutDelegate { final MultiChildLayoutParentData childParentData = child.parentData; assert(() { if (childParentData.id == null) { - throw FlutterError( - 'The following child has no ID:\n' - ' $child\n' - 'Every child of a RenderCustomMultiChildLayoutBox must have an ID in its parent data.' - ); + throw FlutterError.fromParts([ + ErrorSummary('Every child of a RenderCustomMultiChildLayoutBox must have an ID in its parent data.'), + child.describeForError('The following child has no ID'), + ]); } return true; }()); @@ -231,19 +232,17 @@ abstract class MultiChildLayoutDelegate { performLayout(size); assert(() { if (_debugChildrenNeedingLayout.isNotEmpty) { - if (_debugChildrenNeedingLayout.length > 1) { - throw FlutterError( - 'The $this custom multichild layout delegate forgot to lay out the following children:\n' - ' ${_debugChildrenNeedingLayout.map(_debugDescribeChild).join("\n ")}\n' - 'Each child must be laid out exactly once.' - ); - } else { - throw FlutterError( - 'The $this custom multichild layout delegate forgot to lay out the following child:\n' - ' ${_debugDescribeChild(_debugChildrenNeedingLayout.single)}\n' - 'Each child must be laid out exactly once.' - ); - } + throw FlutterError.fromParts([ + ErrorSummary('Each child must be laid out exactly once.'), + DiagnosticsBlock( + name: + 'The $this custom multichild layout delegate forgot ' + 'to lay out the following ' + '${_debugChildrenNeedingLayout.length > 1 ? 'children' : 'child'}', + properties: _debugChildrenNeedingLayout.map(_debugDescribeChild).toList(), + style: DiagnosticsTreeStyle.whitespace, + ), + ]); } return true; }()); diff --git a/packages/flutter/lib/src/rendering/custom_paint.dart b/packages/flutter/lib/src/rendering/custom_paint.dart index 4a5afeab69..a08c9f802b 100644 --- a/packages/flutter/lib/src/rendering/custom_paint.dart +++ b/packages/flutter/lib/src/rendering/custom_paint.dart @@ -539,24 +539,27 @@ class RenderCustomPaint extends RenderProxyBox { // below that number. final int debugNewCanvasSaveCount = canvas.getSaveCount(); if (debugNewCanvasSaveCount > debugPreviousCanvasSaveCount) { - throw FlutterError( - 'The $painter custom painter called canvas.save() or canvas.saveLayer() at least ' - '${debugNewCanvasSaveCount - debugPreviousCanvasSaveCount} more ' - 'time${debugNewCanvasSaveCount - debugPreviousCanvasSaveCount == 1 ? '' : 's' } ' - 'than it called canvas.restore().\n' - 'This leaves the canvas in an inconsistent state and will probably result in a broken display.\n' - 'You must pair each call to save()/saveLayer() with a later matching call to restore().' - ); + throw FlutterError.fromParts([ + ErrorSummary( + 'The $painter custom painter called canvas.save() or canvas.saveLayer() at least ' + '${debugNewCanvasSaveCount - debugPreviousCanvasSaveCount} more ' + 'time${debugNewCanvasSaveCount - debugPreviousCanvasSaveCount == 1 ? '' : 's' } ' + 'than it called canvas.restore().' + ), + ErrorDescription('This leaves the canvas in an inconsistent state and will probably result in a broken display.'), + ErrorHint('You must pair each call to save()/saveLayer() with a later matching call to restore().') + ]); } if (debugNewCanvasSaveCount < debugPreviousCanvasSaveCount) { - throw FlutterError( - 'The $painter custom painter called canvas.restore() ' - '${debugPreviousCanvasSaveCount - debugNewCanvasSaveCount} more ' - 'time${debugPreviousCanvasSaveCount - debugNewCanvasSaveCount == 1 ? '' : 's' } ' - 'than it called canvas.save() or canvas.saveLayer().\n' - 'This leaves the canvas in an inconsistent state and will result in a broken display.\n' - 'You should only call restore() if you first called save() or saveLayer().' - ); + throw FlutterError.fromParts([ + ErrorSummary('The $painter custom painter called canvas.restore() ' + '${debugPreviousCanvasSaveCount - debugNewCanvasSaveCount} more ' + 'time${debugPreviousCanvasSaveCount - debugNewCanvasSaveCount == 1 ? '' : 's' } ' + 'than it called canvas.save() or canvas.saveLayer().' + ), + ErrorDescription('This leaves the canvas in an inconsistent state and will result in a broken display.'), + ErrorHint('You should only call restore() if you first called save() or saveLayer().') + ]); } return debugNewCanvasSaveCount == debugPreviousCanvasSaveCount; }()); @@ -611,10 +614,12 @@ class RenderCustomPaint extends RenderProxyBox { ) { assert(() { if (child == null && children.isNotEmpty) { - throw FlutterError( - '$runtimeType does not have a child widget but received a non-empty list of child SemanticsNode:\n' - '${children.join('\n')}' - ); + throw FlutterError.fromParts([ + ErrorSummary( + '$runtimeType does not have a child widget but received a non-empty list of child SemanticsNode:\n' + '${children.join('\n')}' + ) + ]); } return true; }()); @@ -677,24 +682,20 @@ class RenderCustomPaint extends RenderProxyBox { assert(() { final Map keys = HashMap(); - final StringBuffer errors = StringBuffer(); + final List information = []; for (int i = 0; i < newChildSemantics.length; i += 1) { final CustomPainterSemantics child = newChildSemantics[i]; if (child.key != null) { if (keys.containsKey(child.key)) { - errors.writeln( - '- duplicate key ${child.key} found at position $i', - ); + information.add(ErrorDescription('- duplicate key ${child.key} found at position $i')); } keys[child.key] = i; } } - if (errors.isNotEmpty) { - throw FlutterError( - 'Failed to update the list of CustomPainterSemantics:\n' - '$errors' - ); + if (information.isNotEmpty) { + information.insert(0, ErrorSummary('Failed to update the list of CustomPainterSemantics:')); + throw FlutterError.fromParts(information); } return true; diff --git a/packages/flutter/lib/src/rendering/flow.dart b/packages/flutter/lib/src/rendering/flow.dart index d3550e4495..81e72c8149 100644 --- a/packages/flutter/lib/src/rendering/flow.dart +++ b/packages/flutter/lib/src/rendering/flow.dart @@ -319,11 +319,13 @@ class RenderFlow extends RenderBox final FlowParentData childParentData = child.parentData; assert(() { if (childParentData._transform != null) { - throw FlutterError( - 'Cannot call paintChild twice for the same child.\n' - 'The flow delegate of type ${_delegate.runtimeType} attempted to ' - 'paint child $i multiple times, which is not permitted.' - ); + throw FlutterError.fromParts([ + ErrorSummary('Cannot call paintChild twice for the same child.'), + ErrorDescription( + 'The flow delegate of type ${_delegate.runtimeType} attempted to ' + 'paint child $i multiple times, which is not permitted.' + ) + ]); } return true; }()); diff --git a/packages/flutter/lib/src/rendering/list_body.dart b/packages/flutter/lib/src/rendering/list_body.dart index bac31ef4d7..fc0a6b51f2 100644 --- a/packages/flutter/lib/src/rendering/list_body.dart +++ b/packages/flutter/lib/src/rendering/list_body.dart @@ -74,13 +74,18 @@ class RenderListBody extends RenderBox return true; break; } - throw FlutterError( - 'RenderListBody must have unlimited space along its main axis.\n' - 'RenderListBody does not clip or resize its children, so it must be ' - 'placed in a parent that does not constrain the main ' - 'axis. You probably want to put the RenderListBody inside a ' - 'RenderViewport with a matching main axis.' - ); + throw FlutterError.fromParts([ + ErrorSummary('RenderListBody must have unlimited space along its main axis.'), + ErrorDescription( + 'RenderListBody does not clip or resize its children, so it must be ' + 'placed in a parent that does not constrain the main ' + 'axis.' + ), + ErrorHint( + 'You probably want to put the RenderListBody inside a ' + 'RenderViewport with a matching main axis.' + ) + ]); }()); assert(() { switch (mainAxis) { @@ -96,16 +101,23 @@ class RenderListBody extends RenderBox // TODO(ianh): Detect if we're actually nested blocks and say something // more specific to the exact situation in that case, and don't mention // nesting blocks in the negative case. - throw FlutterError( - 'RenderListBody must have a bounded constraint for its cross axis.\n' - 'RenderListBody forces its children to expand to fit the RenderListBody\'s container, ' - 'so it must be placed in a parent that constrains the cross ' - 'axis to a finite dimension. If you are attempting to nest a RenderListBody with ' - 'one direction inside one of another direction, you will want to ' - 'wrap the inner one inside a box that fixes the dimension in that direction, ' - 'for example, a RenderIntrinsicWidth or RenderIntrinsicHeight object. ' - 'This is relatively expensive, however.' // (that's why we don't do it automatically) - ); + throw FlutterError.fromParts([ + ErrorSummary('RenderListBody must have a bounded constraint for its cross axis.'), + ErrorDescription( + 'RenderListBody forces its children to expand to fit the RenderListBody\'s container, ' + 'so it must be placed in a parent that constrains the cross ' + 'axis to a finite dimension.' + ), + // TODO(jacobr): this hint is a great candidate to promote to being an + // automated quick fix in the future. + ErrorHint( + 'If you are attempting to nest a RenderListBody with ' + 'one direction inside one of another direction, you will want to ' + 'wrap the inner one inside a box that fixes the dimension in that direction, ' + 'for example, a RenderIntrinsicWidth or RenderIntrinsicHeight object. ' + 'This is relatively expensive, however.' // (that's why we don't do it automatically) + ) + ]); }()); double mainAxisExtent = 0.0; RenderBox child = firstChild; diff --git a/packages/flutter/lib/src/rendering/proxy_box.dart b/packages/flutter/lib/src/rendering/proxy_box.dart index 219921b591..5777f1c6c7 100644 --- a/packages/flutter/lib/src/rendering/proxy_box.dart +++ b/packages/flutter/lib/src/rendering/proxy_box.dart @@ -456,13 +456,15 @@ class RenderAspectRatio extends RenderProxyBox { assert(constraints.debugAssertIsValid()); assert(() { if (!constraints.hasBoundedWidth && !constraints.hasBoundedHeight) { - throw FlutterError( - '$runtimeType has unbounded constraints.\n' - 'This $runtimeType was given an aspect ratio of $aspectRatio but was given ' - 'both unbounded width and unbounded height constraints. Because both ' - 'constraints were unbounded, this render object doesn\'t know how much ' - 'size to consume.' - ); + throw FlutterError.fromParts([ + ErrorSummary('$runtimeType has unbounded constraints.'), + ErrorDescription( + 'This $runtimeType was given an aspect ratio of $aspectRatio but was given ' + 'both unbounded width and unbounded height constraints. Because both ' + 'constraints were unbounded, this render object doesn\'t know how much ' + 'size to consume.' + ) + ]); } return true; }()); @@ -1976,16 +1978,16 @@ class RenderDecoratedBox extends RenderProxyBox { _painter.paint(context.canvas, offset, filledConfiguration); assert(() { if (debugSaveCount != context.canvas.getSaveCount()) { - throw FlutterError( - '${_decoration.runtimeType} painter had mismatching save and restore calls.\n' - 'Before painting the decoration, the canvas save count was $debugSaveCount. ' - 'After painting it, the canvas save count was ${context.canvas.getSaveCount()}. ' - 'Every call to save() or saveLayer() must be matched by a call to restore().\n' - 'The decoration was:\n' - ' $decoration\n' - 'The painter was:\n' - ' $_painter' - ); + throw FlutterError.fromParts([ + ErrorSummary('${_decoration.runtimeType} painter had mismatching save and restore calls.'), + ErrorDescription( + 'Before painting the decoration, the canvas save count was $debugSaveCount. ' + 'After painting it, the canvas save count was ${context.canvas.getSaveCount()}. ' + 'Every call to save() or saveLayer() must be matched by a call to restore().' + ), + DiagnosticsProperty('The decoration was', decoration, style: DiagnosticsTreeStyle.errorProperty), + DiagnosticsProperty('The painter was', _painter, style: DiagnosticsTreeStyle.errorProperty), + ]); } return true; }()); diff --git a/packages/flutter/lib/src/rendering/sliver_persistent_header.dart b/packages/flutter/lib/src/rendering/sliver_persistent_header.dart index cf8cc94d76..63427ed05e 100644 --- a/packages/flutter/lib/src/rendering/sliver_persistent_header.dart +++ b/packages/flutter/lib/src/rendering/sliver_persistent_header.dart @@ -132,11 +132,11 @@ abstract class RenderSliverPersistentHeader extends RenderSliver with RenderObje assert(() { if (minExtent <= maxExtent) return true; - throw FlutterError( - 'The maxExtent for this $runtimeType is less than its minExtent.\n' - 'The specified maxExtent was: ${maxExtent.toStringAsFixed(1)}\n' - 'The specified minExtent was: ${minExtent.toStringAsFixed(1)}\n' - ); + throw FlutterError.fromParts([ + ErrorSummary('The maxExtent for this $runtimeType is less than its minExtent.'), + DoubleProperty('The specified maxExtent was', maxExtent), + DoubleProperty('The specified minExtent was', minExtent), + ]); }()); child?.layout( constraints.asBoxConstraints(maxExtent: math.max(minExtent, maxExtent - shrinkOffset)), diff --git a/packages/flutter/lib/src/rendering/viewport.dart b/packages/flutter/lib/src/rendering/viewport.dart index e0172897ec..96ab2f32f9 100644 --- a/packages/flutter/lib/src/rendering/viewport.dart +++ b/packages/flutter/lib/src/rendering/viewport.dart @@ -296,14 +296,18 @@ abstract class RenderViewportBase[ + ErrorSummary('$runtimeType does not support returning intrinsic dimensions.'), + ErrorDescription( + 'Calculating the intrinsic dimensions would require instantiating every child of ' + 'the viewport, which defeats the point of viewports being lazy.', + ), + ErrorHint( + 'If you are merely trying to shrink-wrap the viewport in the main axis direction, ' + 'consider a RenderShrinkWrappingViewport render object (ShrinkWrappingViewport widget), ' + 'which achieves that effect without implementing the intrinsic dimension API.' + ), + ]); } return true; }()); @@ -1165,19 +1169,23 @@ class RenderViewport extends RenderViewportBase[ + ErrorSummary('Vertical viewport was given unbounded height.'), + ErrorDescription( + 'Viewports expand in the scrolling direction to fill their container. ' + 'In this case, a vertical viewport was given an unlimited amount of ' + 'vertical space in which to expand. This situation typically happens ' + 'when a scrollable widget is nested inside another scrollable widget.' + ), + ErrorHint( + 'If this widget is always nested in a scrollable widget there ' + 'is no need to use a viewport because there will always be enough ' + 'vertical space for the children. In this case, consider using a ' + 'Column instead. Otherwise, consider using the "shrinkWrap" property ' + '(or a ShrinkWrappingViewport) to size the height of the viewport ' + 'to the sum of the heights of its children.' + ) + ]); } if (!constraints.hasBoundedWidth) { throw FlutterError( @@ -1191,19 +1199,23 @@ class RenderViewport extends RenderViewportBase[ + ErrorSummary('Horizontal viewport was given unbounded width.'), + ErrorDescription( + 'Viewports expand in the scrolling direction to fill their container.' + 'In this case, a horizontal viewport was given an unlimited amount of ' + 'horizontal space in which to expand. This situation typically happens ' + 'when a scrollable widget is nested inside another scrollable widget.' + ), + ErrorHint( + 'If this widget is always nested in a scrollable widget there ' + 'is no need to use a viewport because there will always be enough ' + 'horizontal space for the children. In this case, consider using a ' + 'Row instead. Otherwise, consider using the "shrinkWrap" property ' + '(or a ShrinkWrappingViewport) to size the width of the viewport ' + 'to the sum of the widths of its children.' + ) + ]); } if (!constraints.hasBoundedHeight) { throw FlutterError( @@ -1585,14 +1597,18 @@ class RenderShrinkWrappingViewport extends RenderViewportBase[ + ErrorSummary('$runtimeType does not support returning intrinsic dimensions.'), + ErrorDescription( + 'Calculating the intrinsic dimensions would require instantiating every child of ' + 'the viewport, which defeats the point of viewports being lazy.' + ), + ErrorHint( + 'If you are merely trying to shrink-wrap the viewport in the main axis direction, ' + 'you should be able to achieve that effect by just giving the viewport loose ' + 'constraints, without needing to measure its intrinsic dimensions.' + ) + ]); } return true; }()); diff --git a/packages/flutter/lib/src/scheduler/binding.dart b/packages/flutter/lib/src/scheduler/binding.dart index f35c5224f0..d31a6f6415 100644 --- a/packages/flutter/lib/src/scheduler/binding.dart +++ b/packages/flutter/lib/src/scheduler/binding.dart @@ -94,15 +94,19 @@ class _FrameCallbackEntry { if (rescheduling) { assert(() { if (debugCurrentCallbackStack == null) { - throw FlutterError( - 'scheduleFrameCallback called with rescheduling true, but no callback is in scope.\n' - 'The "rescheduling" argument should only be set to true if the ' - 'callback is being reregistered from within the callback itself, ' - 'and only then if the callback itself is entirely synchronous. ' - 'If this is the initial registration of the callback, or if the ' - 'callback is asynchronous, then do not use the "rescheduling" ' - 'argument.' - ); + throw FlutterError.fromParts([ + ErrorSummary('scheduleFrameCallback called with rescheduling true, but no callback is in scope.'), + ErrorDescription( + 'The "rescheduling" argument should only be set to true if the ' + 'callback is being reregistered from within the callback itself, ' + 'and only then if the callback itself is entirely synchronous.' + ), + ErrorHint( + 'If this is the initial registration of the callback, or if the ' + 'callback is asynchronous, then do not use the "rescheduling" ' + 'argument.' + ) + ]); } return true; }()); diff --git a/packages/flutter/lib/src/scheduler/ticker.dart b/packages/flutter/lib/src/scheduler/ticker.dart index 40d1b40e18..c3869bc019 100644 --- a/packages/flutter/lib/src/scheduler/ticker.dart +++ b/packages/flutter/lib/src/scheduler/ticker.dart @@ -38,6 +38,8 @@ abstract class TickerProvider { Ticker createTicker(TickerCallback onTick); } +// TODO(jacobr): make Ticker Diagnosticable to simplify reporting errors +// related to a ticker. /// Calls its callback once per animation frame. /// /// When created, a ticker is initially disabled. Call [start] to @@ -145,11 +147,11 @@ class Ticker { TickerFuture start() { assert(() { if (isActive) { - throw FlutterError( - 'A ticker was started twice.\n' - 'A ticker that is already active cannot be started again without first stopping it.\n' - 'The affected ticker was: ${ toString(debugIncludeStack: true) }' - ); + throw FlutterError.fromParts([ + ErrorSummary('A ticker was started twice.'), + ErrorDescription('A ticker that is already active cannot be started again without first stopping it.'), + describeForError('The affected ticker was'), + ]); } return true; }()); @@ -164,6 +166,13 @@ class Ticker { return _future; } + /// Adds a debug representation of a [Ticker] optimized for including in error + /// messages. + DiagnosticsNode describeForError(String name) { + // TODO(jacobr): make this more structured. + return DiagnosticsProperty(name, this, description: toString(debugIncludeStack: true)); + } + /// Stops calling this [Ticker]'s callback. /// /// If called with the `canceled` argument set to false (the default), causes diff --git a/packages/flutter/lib/src/services/asset_bundle.dart b/packages/flutter/lib/src/services/asset_bundle.dart index de2bc05496..3a0df1409f 100644 --- a/packages/flutter/lib/src/services/asset_bundle.dart +++ b/packages/flutter/lib/src/services/asset_bundle.dart @@ -116,10 +116,10 @@ class NetworkAssetBundle extends AssetBundle { final HttpClientRequest request = await _httpClient.getUrl(_urlFromKey(key)); final HttpClientResponse response = await request.close(); if (response.statusCode != HttpStatus.ok) - throw FlutterError( - 'Unable to load asset: $key\n' - 'HTTP status code: ${response.statusCode}' - ); + throw FlutterError.fromParts([ + ErrorSummary('Unable to load asset: $key'), + IntProperty('HTTP status code', response.statusCode), + ]); final Uint8List bytes = await consolidateHttpClientResponseBytes(response); return bytes.buffer.asByteData(); } diff --git a/packages/flutter/lib/src/services/text_input.dart b/packages/flutter/lib/src/services/text_input.dart index d2158a1ab6..d015d81e4c 100644 --- a/packages/flutter/lib/src/services/text_input.dart +++ b/packages/flutter/lib/src/services/text_input.dart @@ -765,7 +765,7 @@ TextInputAction _toTextInputAction(String action) { case 'TextInputAction.newline': return TextInputAction.newline; } - throw FlutterError('Unknown text input action: $action'); + throw FlutterError.fromParts([ErrorSummary('Unknown text input action: $action')]); } FloatingCursorDragState _toTextCursorAction(String state) { @@ -777,7 +777,7 @@ FloatingCursorDragState _toTextCursorAction(String state) { case 'FloatingCursorDragState.end': return FloatingCursorDragState.End; } - throw FlutterError('Unknown text cursor action: $state'); + throw FlutterError.fromParts([ErrorSummary('Unknown text cursor action: $state')]); } RawFloatingCursorPoint _toTextPoint(FloatingCursorDragState state, Map encoded) { diff --git a/packages/flutter/lib/src/widgets/animated_list.dart b/packages/flutter/lib/src/widgets/animated_list.dart index 4be8510427..99384e1283 100644 --- a/packages/flutter/lib/src/widgets/animated_list.dart +++ b/packages/flutter/lib/src/widgets/animated_list.dart @@ -391,16 +391,17 @@ class AnimatedList extends StatefulWidget { final AnimatedListState result = context.ancestorStateOfType(const TypeMatcher()); if (nullOk || result != null) return result; - throw FlutterError( - 'AnimatedList.of() called with a context that does not contain an AnimatedList.\n' - 'No AnimatedList ancestor could be found starting from the context that ' - 'was passed to AnimatedList.of(). This can happen when the context ' - 'provided is from the same StatefulWidget that built the AnimatedList. ' - 'Please see the AnimatedList documentation for examples of how to refer to ' - 'an AnimatedListState object: https://api.flutter.dev/flutter/widgets/AnimatedListState-class.html \n' - 'The context used was:\n' - ' $context' - ); + throw FlutterError.fromParts([ + ErrorSummary('AnimatedList.of() called with a context that does not contain an AnimatedList.'), + ErrorDescription('No AnimatedList ancestor could be found starting from the context that was passed to AnimatedList.of().'), + ErrorHint( + 'This can happen when the context provided is from the same StatefulWidget that ' + 'built the AnimatedList. Please see the AnimatedList documentation for examples ' + 'of how to refer to an AnimatedListState object:' + ' https://api.flutter.dev/flutter/widgets/AnimatedListState-class.html' + ), + context.describeElement('The context used was') + ]); } @override diff --git a/packages/flutter/lib/src/widgets/app.dart b/packages/flutter/lib/src/widgets/app.dart index 7af61b1c17..a15d7ef192 100644 --- a/packages/flutter/lib/src/widgets/app.dart +++ b/packages/flutter/lib/src/widgets/app.dart @@ -783,12 +783,14 @@ class _WidgetsAppState extends State with WidgetsBindingObserver { final Route result = widget.onUnknownRoute(settings); assert(() { if (result == null) { - throw FlutterError( - 'The onUnknownRoute callback returned null.\n' - 'When the $runtimeType requested the route $settings from its ' - 'onUnknownRoute callback, the callback returned null. Such callbacks ' - 'must never return null.' - ); + throw FlutterError.fromParts([ + ErrorSummary('The onUnknownRoute callback returned null.'), + ErrorDescription( + 'When the $runtimeType requested the route $settings from its ' + 'onUnknownRoute callback, the callback returned null. Such callbacks ' + 'must never return null.' + ) + ]); } return true; }()); diff --git a/packages/flutter/lib/src/widgets/binding.dart b/packages/flutter/lib/src/widgets/binding.dart index c9ecc96e42..66c19092f8 100644 --- a/packages/flutter/lib/src/widgets/binding.dart +++ b/packages/flutter/lib/src/widgets/binding.dart @@ -645,23 +645,27 @@ mixin WidgetsBinding on BindingBase, ServicesBinding, SchedulerBinding, GestureB // should not trigger a new frame. assert(() { if (debugBuildingDirtyElements) { - throw FlutterError( - 'Build scheduled during frame.\n' - 'While the widget tree was being built, laid out, and painted, ' - 'a new frame was scheduled to rebuild the widget tree. ' - 'This might be because setState() was called from a layout or ' - 'paint callback. ' - 'If a change is needed to the widget tree, it should be applied ' - 'as the tree is being built. Scheduling a change for the subsequent ' - 'frame instead results in an interface that lags behind by one frame. ' - 'If this was done to make your build dependent on a size measured at ' - 'layout time, consider using a LayoutBuilder, CustomSingleChildLayout, ' - 'or CustomMultiChildLayout. If, on the other hand, the one frame delay ' - 'is the desired effect, for example because this is an ' - 'animation, consider scheduling the frame in a post-frame callback ' - 'using SchedulerBinding.addPostFrameCallback or ' - 'using an AnimationController to trigger the animation.' - ); + throw FlutterError.fromParts([ + ErrorSummary('Build scheduled during frame.'), + ErrorDescription( + 'While the widget tree was being built, laid out, and painted, ' + 'a new frame was scheduled to rebuild the widget tree.' + ), + ErrorHint( + 'This might be because setState() was called from a layout or ' + 'paint callback. ' + 'If a change is needed to the widget tree, it should be applied ' + 'as the tree is being built. Scheduling a change for the subsequent ' + 'frame instead results in an interface that lags behind by one frame. ' + 'If this was done to make your build dependent on a size measured at ' + 'layout time, consider using a LayoutBuilder, CustomSingleChildLayout, ' + 'or CustomMultiChildLayout. If, on the other hand, the one frame delay ' + 'is the desired effect, for example because this is an ' + 'animation, consider scheduling the frame in a post-frame callback ' + 'using SchedulerBinding.addPostFrameCallback or ' + 'using an AnimationController to trigger the animation.', + ) + ]); } return true; }()); diff --git a/packages/flutter/lib/src/widgets/debug.dart b/packages/flutter/lib/src/widgets/debug.dart index f2aa211702..e06f1251f6 100644 --- a/packages/flutter/lib/src/widgets/debug.dart +++ b/packages/flutter/lib/src/widgets/debug.dart @@ -5,6 +5,8 @@ import 'dart:collection'; import 'dart:developer' show Timeline; // to disambiguate reference in dartdocs below +import 'package:flutter/foundation.dart'; + import 'basic.dart'; import 'framework.dart'; import 'media_query.dart'; @@ -126,11 +128,13 @@ bool debugChildrenHaveDuplicateKeys(Widget parent, Iterable children) { assert(() { final Key nonUniqueKey = _firstNonUniqueKey(children); if (nonUniqueKey != null) { - throw FlutterError( - 'Duplicate keys found.\n' - 'If multiple keyed nodes exist as children of another node, they must have unique keys.\n' - '$parent has multiple children with key $nonUniqueKey.' - ); + throw FlutterError.fromParts([ + ErrorSummary('Duplicate keys found.'), + ErrorDescription( + 'If multiple keyed nodes exist as children of another node, they must have unique keys.\n' + '$parent has multiple children with key $nonUniqueKey.' + ), + ]); } return true; }()); @@ -153,7 +157,9 @@ bool debugItemsHaveDuplicateKeys(Iterable items) { assert(() { final Key nonUniqueKey = _firstNonUniqueKey(items); if (nonUniqueKey != null) - throw FlutterError('Duplicate key found: $nonUniqueKey.'); + throw FlutterError.fromParts([ + ErrorSummary('Duplicate key found: $nonUniqueKey.'), + ]); return true; }()); return false; @@ -174,15 +180,12 @@ bool debugItemsHaveDuplicateKeys(Iterable items) { bool debugCheckHasTable(BuildContext context) { assert(() { if (context.widget is! Table && context.ancestorWidgetOfExactType(Table) == null) { - final Element element = context; - throw FlutterError( - 'No Table widget found.\n' - '${context.widget.runtimeType} widgets require a Table widget ancestor.\n' - 'The specific widget that could not find a Table ancestor was:\n' - ' ${context.widget}\n' - 'The ownership chain for the affected widget is:\n' - ' ${element.debugGetCreatorChain(10)}' - ); + throw FlutterError.fromParts([ + ErrorSummary('No Table widget found.'), + ErrorDescription('${context.widget.runtimeType} widgets require a Table widget ancestor.'), + context.describeWidget('The specific widget that could not find a Table ancestor was'), + context.describeOwnershipChain('The ownership chain for the affected widget is'), + ]); } return true; }()); @@ -205,17 +208,16 @@ bool debugCheckHasTable(BuildContext context) { bool debugCheckHasMediaQuery(BuildContext context) { assert(() { if (context.widget is! MediaQuery && context.ancestorWidgetOfExactType(MediaQuery) == null) { - final Element element = context; - throw FlutterError( - 'No MediaQuery widget found.\n' - '${context.widget.runtimeType} widgets require a MediaQuery widget ancestor.\n' - 'The specific widget that could not find a MediaQuery ancestor was:\n' - ' ${context.widget}\n' - 'The ownership chain for the affected widget is:\n' - ' ${element.debugGetCreatorChain(10)}\n' - 'Typically, the MediaQuery widget is introduced by the MaterialApp or ' - 'WidgetsApp widget at the top of your application widget tree.' - ); + throw FlutterError.fromParts([ + ErrorSummary('No MediaQuery widget found.'), + ErrorDescription('${context.widget.runtimeType} widgets require a MediaQuery widget ancestor.'), + context.describeWidget('The specific widget that could not find a MediaQuery ancestor was'), + context.describeOwnershipChain('The ownership chain for the affected widget is'), + ErrorHint( + 'Typically, the MediaQuery widget is introduced by the MaterialApp or ' + 'WidgetsApp widget at the top of your application widget tree.' + ), + ]); } return true; }()); @@ -238,21 +240,20 @@ bool debugCheckHasMediaQuery(BuildContext context) { bool debugCheckHasDirectionality(BuildContext context) { assert(() { if (context.widget is! Directionality && context.ancestorWidgetOfExactType(Directionality) == null) { - final Element element = context; - throw FlutterError( - 'No Directionality widget found.\n' - '${context.widget.runtimeType} widgets require a Directionality widget ancestor.\n' - 'The specific widget that could not find a Directionality ancestor was:\n' - ' ${context.widget}\n' - 'The ownership chain for the affected widget is:\n' - ' ${element.debugGetCreatorChain(10)}\n' - 'Typically, the Directionality widget is introduced by the MaterialApp ' - 'or WidgetsApp widget at the top of your application widget tree. It ' - 'determines the ambient reading direction and is used, for example, to ' - 'determine how to lay out text, how to interpret "start" and "end" ' - 'values, and to resolve EdgeInsetsDirectional, ' - 'AlignmentDirectional, and other *Directional objects.' - ); + throw FlutterError.fromParts([ + ErrorSummary('No Directionality widget found.'), + ErrorDescription('${context.widget.runtimeType} widgets require a Directionality widget ancestor.\n'), + context.describeWidget('The specific widget that could not find a Directionality ancestor was'), + context.describeOwnershipChain('The ownership chain for the affected widget is'), + ErrorHint( + 'Typically, the Directionality widget is introduced by the MaterialApp ' + 'or WidgetsApp widget at the top of your application widget tree. It ' + 'determines the ambient reading direction and is used, for example, to ' + 'determine how to lay out text, how to interpret "start" and "end" ' + 'values, and to resolve EdgeInsetsDirectional, ' + 'AlignmentDirectional, and other *Directional objects.' + ), + ]); } return true; }()); @@ -268,21 +269,25 @@ bool debugCheckHasDirectionality(BuildContext context) { void debugWidgetBuilderValue(Widget widget, Widget built) { assert(() { if (built == null) { - throw FlutterError( - 'A build function returned null.\n' - 'The offending widget is: $widget\n' - 'Build functions must never return null. ' - 'To return an empty space that causes the building widget to fill available room, return "new Container()". ' - 'To return an empty space that takes as little room as possible, return "new Container(width: 0.0, height: 0.0)".' - ); + throw FlutterError.fromParts([ + ErrorSummary('A build function returned null.'), + DiagnosticsProperty('The offending widget is', widget, style: DiagnosticsTreeStyle.errorProperty), + ErrorDescription('Build functions must never return null.'), + ErrorHint( + 'To return an empty space that causes the building widget to fill available room, return "Container()". ' + 'To return an empty space that takes as little room as possible, return "Container(width: 0.0, height: 0.0)".' + ), + ]); } if (widget == built) { - throw FlutterError( - 'A build function returned context.widget.\n' - 'The offending widget is: $widget\n' - 'Build functions must never return their BuildContext parameter\'s widget or a child that contains "context.widget". ' - 'Doing so introduces a loop in the widget tree that can cause the app to crash.' - ); + throw FlutterError.fromParts([ + ErrorSummary('A build function returned context.widget.'), + DiagnosticsProperty('The offending widget is', widget, style: DiagnosticsTreeStyle.errorProperty), + ErrorDescription( + 'Build functions must never return their BuildContext parameter\'s widget or a child that contains "context.widget". ' + 'Doing so introduces a loop in the widget tree that can cause the app to crash.' + ), + ]); } return true; }()); @@ -302,7 +307,7 @@ bool debugAssertAllWidgetVarsUnset(String reason) { debugPrintGlobalKeyedWidgetLifecycle || debugProfileBuildsEnabled || debugHighlightDeprecatedWidgets) { - throw FlutterError(reason); + throw FlutterError.fromParts([ErrorSummary('$reason')]); } return true; }()); diff --git a/packages/flutter/lib/src/widgets/dismissible.dart b/packages/flutter/lib/src/widgets/dismissible.dart index 4333d9ce1a..fa363fdcb3 100644 --- a/packages/flutter/lib/src/widgets/dismissible.dart +++ b/packages/flutter/lib/src/widgets/dismissible.dart @@ -523,11 +523,13 @@ class _DismissibleState extends State with TickerProviderStateMixin assert(() { if (_resizeAnimation.status != AnimationStatus.forward) { assert(_resizeAnimation.status == AnimationStatus.completed); - throw FlutterError( - 'A dismissed Dismissible widget is still part of the tree.\n' - 'Make sure to implement the onDismissed handler and to immediately remove the Dismissible\n' - 'widget from the application once that handler has fired.' - ); + throw FlutterError.fromParts([ + ErrorSummary('A dismissed Dismissible widget is still part of the tree.'), + ErrorHint( + 'Make sure to implement the onDismissed handler and to immediately remove the Dismissible ' + 'widget from the application once that handler has fired.' + ) + ]); } return true; }()); diff --git a/packages/flutter/lib/src/widgets/editable_text.dart b/packages/flutter/lib/src/widgets/editable_text.dart index 7a1b0fcade..0f38f56c16 100644 --- a/packages/flutter/lib/src/widgets/editable_text.dart +++ b/packages/flutter/lib/src/widgets/editable_text.dart @@ -190,7 +190,7 @@ class TextEditingController extends ValueNotifier { /// change the controller's [value]. set selection(TextSelection newSelection) { if (newSelection.start > text.length || newSelection.end > text.length) - throw FlutterError('invalid text selection: $newSelection'); + throw FlutterError.fromParts([ErrorSummary('invalid text selection: $newSelection')]); value = value.copyWith(selection: newSelection, composing: TextRange.empty); } diff --git a/packages/flutter/lib/src/widgets/gesture_detector.dart b/packages/flutter/lib/src/widgets/gesture_detector.dart index b848f826be..a5b14e3dcb 100644 --- a/packages/flutter/lib/src/widgets/gesture_detector.dart +++ b/packages/flutter/lib/src/widgets/gesture_detector.dart @@ -232,18 +232,23 @@ class GestureDetector extends StatelessWidget { final bool haveScale = onScaleStart != null || onScaleUpdate != null || onScaleEnd != null; if (havePan || haveScale) { if (havePan && haveScale) { - throw FlutterError( - 'Incorrect GestureDetector arguments.\n' - 'Having both a pan gesture recognizer and a scale gesture recognizer is redundant; scale is a superset of pan. Just use the scale gesture recognizer.' - ); + throw FlutterError.fromParts([ + ErrorSummary('Incorrect GestureDetector arguments.'), + ErrorDescription( + 'Having both a pan gesture recognizer and a scale gesture recognizer is redundant; scale is a superset of pan.' + ), + ErrorHint('Just use the scale gesture recognizer.') + ]); } final String recognizer = havePan ? 'pan' : 'scale'; if (haveVerticalDrag && haveHorizontalDrag) { - throw FlutterError( - 'Incorrect GestureDetector arguments.\n' - 'Simultaneously having a vertical drag gesture recognizer, a horizontal drag gesture recognizer, and a $recognizer gesture recognizer ' - 'will result in the $recognizer gesture recognizer being ignored, since the other two will catch all drags.' - ); + throw FlutterError.fromParts([ + ErrorSummary('Incorrect GestureDetector arguments.'), + ErrorDescription( + 'Simultaneously having a vertical drag gesture recognizer, a horizontal drag gesture recognizer, and a $recognizer gesture recognizer ' + 'will result in the $recognizer gesture recognizer being ignored, since the other two will catch all drags.' + ) + ]); } } return true; @@ -935,13 +940,15 @@ class RawGestureDetectorState extends State { void replaceGestureRecognizers(Map gestures) { assert(() { if (!context.findRenderObject().owner.debugDoingLayout) { - throw FlutterError( - 'Unexpected call to replaceGestureRecognizers() method of RawGestureDetectorState.\n' - 'The replaceGestureRecognizers() method can only be called during the layout phase. ' - 'To set the gesture recognizers at other times, trigger a new build using setState() ' - 'and provide the new gesture recognizers as constructor arguments to the corresponding ' - 'RawGestureDetector or GestureDetector object.' - ); + throw FlutterError.fromParts([ + ErrorSummary('Unexpected call to replaceGestureRecognizers() method of RawGestureDetectorState.'), + ErrorDescription('The replaceGestureRecognizers() method can only be called during the layout phase.'), + ErrorHint( + 'To set the gesture recognizers at other times, trigger a new build using setState() ' + 'and provide the new gesture recognizers as constructor arguments to the corresponding ' + 'RawGestureDetector or GestureDetector object.' + ) + ]); } return true; }()); diff --git a/packages/flutter/lib/src/widgets/heroes.dart b/packages/flutter/lib/src/widgets/heroes.dart index 749eaad605..aa7bdfeb48 100644 --- a/packages/flutter/lib/src/widgets/heroes.dart +++ b/packages/flutter/lib/src/widgets/heroes.dart @@ -262,14 +262,15 @@ class Hero extends StatefulWidget { void inviteHero(StatefulElement hero, Object tag) { assert(() { if (result.containsKey(tag)) { - throw FlutterError( - 'There are multiple heroes that share the same tag within a subtree.\n' - 'Within each subtree for which heroes are to be animated (i.e. a PageRoute subtree), ' - 'each Hero must have a unique non-null tag.\n' - 'In this case, multiple heroes had the following tag: $tag\n' - 'Here is the subtree for one of the offending heroes:\n' - '${hero.toStringDeep(prefixLineOne: "# ")}' - ); + throw FlutterError.fromParts([ + ErrorSummary('There are multiple heroes that share the same tag within a subtree.'), + ErrorDescription( + 'Within each subtree for which heroes are to be animated (i.e. a PageRoute subtree), ' + 'each Hero must have a unique non-null tag.\n' + 'In this case, multiple heroes had the following tag: $tag\n' + ), + DiagnosticsProperty('Here is the subtree for one of the offending heroes', hero, linePrefix: '# ', style: DiagnosticsTreeStyle.dense), + ]); } return true; }()); diff --git a/packages/flutter/lib/src/widgets/media_query.dart b/packages/flutter/lib/src/widgets/media_query.dart index 042eecff35..46c86fec5e 100644 --- a/packages/flutter/lib/src/widgets/media_query.dart +++ b/packages/flutter/lib/src/widgets/media_query.dart @@ -795,15 +795,16 @@ class MediaQuery extends InheritedWidget { return query.data; if (nullOk) return null; - throw FlutterError( - 'MediaQuery.of() called with a context that does not contain a MediaQuery.\n' - 'No MediaQuery ancestor could be found starting from the context that was passed ' - 'to MediaQuery.of(). This can happen because you do not have a WidgetsApp or ' - 'MaterialApp widget (those widgets introduce a MediaQuery), or it can happen ' - 'if the context you use comes from a widget above those widgets.\n' - 'The context used was:\n' - ' $context' - ); + throw FlutterError.fromParts([ + ErrorSummary('MediaQuery.of() called with a context that does not contain a MediaQuery.'), + ErrorDescription( + 'No MediaQuery ancestor could be found starting from the context that was passed ' + 'to MediaQuery.of(). This can happen because you do not have a WidgetsApp or ' + 'MaterialApp widget (those widgets introduce a MediaQuery), or it can happen ' + 'if the context you use comes from a widget above those widgets.' + ), + context.describeElement('The context used was') + ]); } /// Returns textScaleFactor for the nearest MediaQuery ancestor or 1.0, if diff --git a/packages/flutter/lib/src/widgets/navigator.dart b/packages/flutter/lib/src/widgets/navigator.dart index 315d3e6979..2ede2fdfc2 100644 --- a/packages/flutter/lib/src/widgets/navigator.dart +++ b/packages/flutter/lib/src/widgets/navigator.dart @@ -1630,26 +1630,28 @@ class NavigatorState extends State with TickerProviderStateMixin { if (route == null && !allowNull) { assert(() { if (widget.onUnknownRoute == null) { - throw FlutterError( - 'If a Navigator has no onUnknownRoute, then its onGenerateRoute must never return null.\n' - 'When trying to build the route "$name", onGenerateRoute returned null, but there was no ' - 'onUnknownRoute callback specified.\n' - 'The Navigator was:\n' - ' $this' - ); + throw FlutterError.fromParts([ + ErrorSummary('If a Navigator has no onUnknownRoute, then its onGenerateRoute must never return null.'), + ErrorDescription( + 'When trying to build the route "$name", onGenerateRoute returned null, but there was no ' + 'onUnknownRoute callback specified.' + ), + DiagnosticsProperty('The Navigator was', this, style: DiagnosticsTreeStyle.errorProperty), + ]); } return true; }()); route = widget.onUnknownRoute(settings); assert(() { if (route == null) { - throw FlutterError( - 'A Navigator\'s onUnknownRoute returned null.\n' - 'When trying to build the route "$name", both onGenerateRoute and onUnknownRoute returned ' - 'null. The onUnknownRoute callback should never return null.\n' - 'The Navigator was:\n' - ' $this' - ); + throw FlutterError.fromParts([ + ErrorSummary('A Navigator\'s onUnknownRoute returned null.'), + ErrorDescription( + 'When trying to build the route "$name", both onGenerateRoute and onUnknownRoute returned ' + 'null. The onUnknownRoute callback should never return null.' + ), + DiagnosticsProperty('The Navigator was', this, style: DiagnosticsTreeStyle.errorProperty), + ]); } return true; }()); diff --git a/packages/flutter/lib/src/widgets/overlay.dart b/packages/flutter/lib/src/widgets/overlay.dart index c1f1cd37d1..af2f19f49c 100644 --- a/packages/flutter/lib/src/widgets/overlay.dart +++ b/packages/flutter/lib/src/widgets/overlay.dart @@ -238,17 +238,16 @@ class Overlay extends StatefulWidget { final OverlayState result = context.ancestorStateOfType(const TypeMatcher()); assert(() { if (debugRequiredFor != null && result == null) { - final String additional = context.widget != debugRequiredFor - ? '\nThe context from which that widget was searching for an overlay was:\n $context' - : ''; - throw FlutterError( - 'No Overlay widget found.\n' - '${debugRequiredFor.runtimeType} widgets require an Overlay widget ancestor for correct operation.\n' - 'The most common way to add an Overlay to an application is to include a MaterialApp or Navigator widget in the runApp() call.\n' - 'The specific widget that failed to find an overlay was:\n' - ' $debugRequiredFor' - '$additional' - ); + final List information = [ + ErrorSummary('No Overlay widget found.'), + ErrorDescription('${debugRequiredFor.runtimeType} widgets require an Overlay widget ancestor for correct operation.'), + ErrorHint('The most common way to add an Overlay to an application is to include a MaterialApp or Navigator widget in the runApp() call.'), + DiagnosticsProperty('The specific widget that failed to find an overlay was', debugRequiredFor, style: DiagnosticsTreeStyle.errorProperty), + if (context.widget != debugRequiredFor) + context.describeElement('The context from which that widget was searching for an overlay was') + ]; + + throw FlutterError.fromParts(information); } return true; }()); diff --git a/packages/flutter/lib/src/widgets/scroll_physics.dart b/packages/flutter/lib/src/widgets/scroll_physics.dart index a8a16b87ec..3430dd917e 100644 --- a/packages/flutter/lib/src/widgets/scroll_physics.dart +++ b/packages/flutter/lib/src/widgets/scroll_physics.dart @@ -422,17 +422,17 @@ class ClampingScrollPhysics extends ScrollPhysics { double applyBoundaryConditions(ScrollMetrics position, double value) { assert(() { if (value == position.pixels) { - throw FlutterError( - '$runtimeType.applyBoundaryConditions() was called redundantly.\n' - 'The proposed new position, $value, is exactly equal to the current position of the ' - 'given ${position.runtimeType}, ${position.pixels}.\n' - 'The applyBoundaryConditions method should only be called when the value is ' - 'going to actually change the pixels, otherwise it is redundant.\n' - 'The physics object in question was:\n' - ' $this\n' - 'The position object in question was:\n' - ' $position' - ); + throw FlutterError.fromParts([ + ErrorSummary('$runtimeType.applyBoundaryConditions() was called redundantly.'), + ErrorDescription( + 'The proposed new position, $value, is exactly equal to the current position of the ' + 'given ${position.runtimeType}, ${position.pixels}.\n' + 'The applyBoundaryConditions method should only be called when the value is ' + 'going to actually change the pixels, otherwise it is redundant.' + ), + DiagnosticsProperty('The physics object in question was', this, style: DiagnosticsTreeStyle.errorProperty), + DiagnosticsProperty('The position object in question was', position, style: DiagnosticsTreeStyle.errorProperty) + ]); } return true; }()); diff --git a/packages/flutter/lib/src/widgets/scroll_position.dart b/packages/flutter/lib/src/widgets/scroll_position.dart index d5731a00c0..f1ade32c8f 100644 --- a/packages/flutter/lib/src/widgets/scroll_position.dart +++ b/packages/flutter/lib/src/widgets/scroll_position.dart @@ -203,12 +203,14 @@ abstract class ScrollPosition extends ViewportOffset with ScrollMetrics { assert(() { final double delta = newPixels - pixels; if (overscroll.abs() > delta.abs()) { - throw FlutterError( - '$runtimeType.applyBoundaryConditions returned invalid overscroll value.\n' - 'setPixels() was called to change the scroll offset from $pixels to $newPixels.\n' - 'That is a delta of $delta units.\n' - '$runtimeType.applyBoundaryConditions reported an overscroll of $overscroll units.' - ); + throw FlutterError.fromParts([ + ErrorSummary('$runtimeType.applyBoundaryConditions returned invalid overscroll value.'), + ErrorDescription( + 'setPixels() was called to change the scroll offset from $pixels to $newPixels.\n' + 'That is a delta of $delta units.\n' + '$runtimeType.applyBoundaryConditions reported an overscroll of $overscroll units.' + ) + ]); } return true; }()); @@ -374,16 +376,18 @@ abstract class ScrollPosition extends ViewportOffset with ScrollMetrics { assert(() { final double delta = value - pixels; if (result.abs() > delta.abs()) { - throw FlutterError( - '${physics.runtimeType}.applyBoundaryConditions returned invalid overscroll value.\n' - 'The method was called to consider a change from $pixels to $value, which is a ' - 'delta of ${delta.toStringAsFixed(1)} units. However, it returned an overscroll of ' - '${result.toStringAsFixed(1)} units, which has a greater magnitude than the delta. ' - 'The applyBoundaryConditions method is only supposed to reduce the possible range ' - 'of movement, not increase it.\n' - 'The scroll extents are $minScrollExtent .. $maxScrollExtent, and the ' - 'viewport dimension is $viewportDimension.' - ); + throw FlutterError.fromParts([ + ErrorSummary('${physics.runtimeType}.applyBoundaryConditions returned invalid overscroll value.'), + ErrorDescription( + 'The method was called to consider a change from $pixels to $value, which is a ' + 'delta of ${delta.toStringAsFixed(1)} units. However, it returned an overscroll of ' + '${result.toStringAsFixed(1)} units, which has a greater magnitude than the delta. ' + 'The applyBoundaryConditions method is only supposed to reduce the possible range ' + 'of movement, not increase it.\n' + 'The scroll extents are $minScrollExtent .. $maxScrollExtent, and the ' + 'viewport dimension is $viewportDimension.' + ) + ]); } return true; }()); diff --git a/packages/flutter/lib/src/widgets/ticker_provider.dart b/packages/flutter/lib/src/widgets/ticker_provider.dart index 06d1364720..a7d50dac87 100644 --- a/packages/flutter/lib/src/widgets/ticker_provider.dart +++ b/packages/flutter/lib/src/widgets/ticker_provider.dart @@ -82,13 +82,15 @@ mixin SingleTickerProviderStateMixin on State imple assert(() { if (_ticker == null) return true; - throw FlutterError( - '$runtimeType is a SingleTickerProviderStateMixin but multiple tickers were created.\n' - 'A SingleTickerProviderStateMixin can only be used as a TickerProvider once. If a ' - 'State is used for multiple AnimationController objects, or if it is passed to other ' - 'objects and those objects might use it more than one time in total, then instead of ' - 'mixing in a SingleTickerProviderStateMixin, use a regular TickerProviderStateMixin.' - ); + throw FlutterError.fromParts([ + ErrorSummary('$runtimeType is a SingleTickerProviderStateMixin but multiple tickers were created.'), + ErrorDescription('A SingleTickerProviderStateMixin can only be used as a TickerProvider once.'), + ErrorHint( + 'If a State is used for multiple AnimationController objects, or if it is passed to other ' + 'objects and those objects might use it more than one time in total, then instead of ' + 'mixing in a SingleTickerProviderStateMixin, use a regular TickerProviderStateMixin.' + ) + ]); }()); _ticker = Ticker(onTick, debugLabel: kDebugMode ? 'created by $this' : null); // We assume that this is called from initState, build, or some sort of @@ -103,15 +105,20 @@ mixin SingleTickerProviderStateMixin on State imple assert(() { if (_ticker == null || !_ticker.isActive) return true; - throw FlutterError( - '$this was disposed with an active Ticker.\n' - '$runtimeType created a Ticker via its SingleTickerProviderStateMixin, but at the time ' - 'dispose() was called on the mixin, that Ticker was still active. The Ticker must ' - 'be disposed before calling super.dispose(). Tickers used by AnimationControllers ' - 'should be disposed by calling dispose() on the AnimationController itself. ' - 'Otherwise, the ticker will leak.\n' - 'The offending ticker was: ${_ticker.toString(debugIncludeStack: true)}' - ); + throw FlutterError.fromParts([ + ErrorSummary('$this was disposed with an active Ticker.'), + ErrorDescription( + '$runtimeType created a Ticker via its SingleTickerProviderStateMixin, but at the time ' + 'dispose() was called on the mixin, that Ticker was still active. The Ticker must ' + 'be disposed before calling super.dispose().' + ), + ErrorHint( + 'Tickers used by AnimationControllers ' + 'should be disposed by calling dispose() on the AnimationController itself. ' + 'Otherwise, the ticker will leak.' + ), + _ticker.describeForError('The offending ticker was') + ]); }()); super.dispose(); } @@ -175,15 +182,20 @@ mixin TickerProviderStateMixin on State implements if (_tickers != null) { for (Ticker ticker in _tickers) { if (ticker.isActive) { - throw FlutterError( - '$this was disposed with an active Ticker.\n' - '$runtimeType created a Ticker via its TickerProviderStateMixin, but at the time ' - 'dispose() was called on the mixin, that Ticker was still active. All Tickers must ' - 'be disposed before calling super.dispose(). Tickers used by AnimationControllers ' - 'should be disposed by calling dispose() on the AnimationController itself. ' - 'Otherwise, the ticker will leak.\n' - 'The offending ticker was: ${ticker.toString(debugIncludeStack: true)}' - ); + throw FlutterError.fromParts([ + ErrorSummary('$this was disposed with an active Ticker.'), + ErrorDescription( + '$runtimeType created a Ticker via its TickerProviderStateMixin, but at the time ' + 'dispose() was called on the mixin, that Ticker was still active. All Tickers must ' + 'be disposed before calling super.dispose().' + ), + ErrorHint( + 'Tickers used by AnimationControllers ' + 'should be disposed by calling dispose() on the AnimationController itself. ' + 'Otherwise, the ticker will leak.' + ), + ticker.describeForError('The offending ticker was'), + ]); } } } diff --git a/packages/flutter/test/animation/animations_test.dart b/packages/flutter/test/animation/animations_test.dart index 8d86c431d9..63bdfe8282 100644 --- a/packages/flutter/test/animation/animations_test.dart +++ b/packages/flutter/test/animation/animations_test.dart @@ -238,8 +238,26 @@ void main() { vsync: const TestVSync(), ); final CurvedAnimation curved = CurvedAnimation(parent: controller, curve: BogusCurve()); - - expect(() { curved.value; }, throwsFlutterError); + FlutterError error; + try { + curved.value; + } on FlutterError catch (e) { + error = e; + } + expect(error, isNotNull); + expect(error.toStringDeep(), matches( + // RegExp matcher is required here due to flutter web and flutter mobile generating + // slightly different floating point numbers + // in Flutter web 0.0 sometimes just appears as 0. or 0 + RegExp( + r'''FlutterError + Invalid curve endpoint at \d+(\.\d*)?\. + Curves must map 0\.0 to near zero and 1\.0 to near one but + BogusCurve mapped \d+(\.\d*)? to \d+(\.\d*)?, which is near \d+(\.\d*)?\. +''', + multiLine: true + ), + )); }); test('CurvedAnimation running with different forward and reverse durations.', () { diff --git a/packages/flutter/test/cupertino/tab_test.dart b/packages/flutter/test/cupertino/tab_test.dart index d58fb53b9b..7bbb1563a1 100644 --- a/packages/flutter/test/cupertino/tab_test.dart +++ b/packages/flutter/test/cupertino/tab_test.dart @@ -167,4 +167,68 @@ void main() { expect(find.text('go to second page'), findsOneWidget); expect(find.text('second route'), findsNothing); }); + + testWidgets('Throws FlutterError when onUnknownRoute is null', ( + WidgetTester tester) async { + final GlobalKey key = GlobalKey(); + await tester.pumpWidget( + CupertinoApp( + home: CupertinoTabView( + navigatorKey: key, + builder: (BuildContext context) => const Text('first route'), + onUnknownRoute: null, + ), + ), + ); + FlutterError error; + try { + key.currentState.pushNamed('/2'); + } on FlutterError catch (e) { + error = e; + } + expect(error, isNotNull); + expect(error.toStringDeep(), equalsIgnoringHashCodes( + 'FlutterError\n' + ' Could not find a generator for route RouteSettings("/2", null) in\n' + ' the _CupertinoTabViewState.\n' + ' Generators for routes are searched for in the following order:\n' + ' 1. For the "/" route, the "builder" property, if non-null, is\n' + ' used.\n' + ' 2. Otherwise, the "routes" table is used, if it has an entry for\n' + ' the route.\n' + ' 3. Otherwise, onGenerateRoute is called. It should return a\n' + ' non-null value for any valid route not handled by "builder" and\n' + ' "routes".\n' + ' 4. Finally if all else fails onUnknownRoute is called.\n' + ' Unfortunately, onUnknownRoute was not set.\n' + )); + }); + + testWidgets('Throws FlutterError when onUnknownRoute returns null', ( + WidgetTester tester) async { + final GlobalKey key = GlobalKey(); + await tester.pumpWidget( + CupertinoApp( + home: CupertinoTabView( + navigatorKey: key, + builder: (BuildContext context) => const Text('first route'), + onUnknownRoute: (_) => null, + ), + ), + ); + FlutterError error; + try { + key.currentState.pushNamed('/2'); + } on FlutterError catch (e) { + error = e; + } + expect(error, isNotNull); + expect(error.toStringDeep(), equalsIgnoringHashCodes( + 'FlutterError\n' + ' The onUnknownRoute callback returned null.\n' + ' When the _CupertinoTabViewState requested the route\n' + ' RouteSettings("/2", null) from its onUnknownRoute callback, the\n' + ' callback returned null. Such callbacks must never return null.\n' + )); + }); } diff --git a/packages/flutter/test/foundation/change_notifier_test.dart b/packages/flutter/test/foundation/change_notifier_test.dart index d0ef104665..f9d5387010 100644 --- a/packages/flutter/test/foundation/change_notifier_test.dart +++ b/packages/flutter/test/foundation/change_notifier_test.dart @@ -315,4 +315,24 @@ void main() { expect(b.result, isTrue); expect(notifications, 1); }); + + test('Throws FlutterError when disposed and called', () { + final TestNotifier testNotifier = TestNotifier(); + testNotifier.dispose(); + FlutterError error; + try { + testNotifier.dispose(); + } on FlutterError catch (e) { + error = e; + } + expect(error, isNotNull); + expect(error, isFlutterError); + expect(error.toStringDeep(), equalsIgnoringHashCodes( + 'FlutterError\n' + ' A TestNotifier was used after being disposed.\n' + ' Once you have called dispose() on a TestNotifier, it can no\n' + ' longer be used.\n' + )); + }); + } diff --git a/packages/flutter/test/material/debug_test.dart b/packages/flutter/test/material/debug_test.dart index 847e16ce1b..9a361150d7 100644 --- a/packages/flutter/test/material/debug_test.dart +++ b/packages/flutter/test/material/debug_test.dart @@ -2,6 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; @@ -10,7 +11,170 @@ void main() { await tester.pumpWidget(const ListTile()); final dynamic exception = tester.takeException(); expect(exception, isFlutterError); - expect(exception.toString(), startsWith('No Material widget found.')); - expect(exception.toString(), endsWith(':\n ListTile\nThe ancestors of this widget were:\n [root]')); + final FlutterError error = exception; + expect(error.diagnostics.length, 5); + expect(error.diagnostics[2].level, DiagnosticLevel.hint); + expect( + error.diagnostics[2].toStringDeep(), + equalsIgnoringHashCodes( + 'To introduce a Material widget, you can either directly include\n' + 'one, or use a widget that contains Material itself, such as a\n' + 'Card, Dialog, Drawer, or Scaffold.\n', + ), + ); + expect(error.diagnostics[3], isInstanceOf>()); + expect(error.diagnostics[4], isInstanceOf()); + expect(error.toStringDeep(), + 'FlutterError\n' + ' No Material widget found.\n' + ' ListTile widgets require a Material widget ancestor.\n' + ' In material design, most widgets are conceptually "printed" on a\n' + ' sheet of material. In Flutter\'s material library, that material\n' + ' is represented by the Material widget. It is the Material widget\n' + ' that renders ink splashes, for instance. Because of this, many\n' + ' material library widgets require that there be a Material widget\n' + ' in the tree above them.\n' + ' To introduce a Material widget, you can either directly include\n' + ' one, or use a widget that contains Material itself, such as a\n' + ' Card, Dialog, Drawer, or Scaffold.\n' + ' The specific widget that could not find a Material ancestor was:\n' + ' ListTile\n' + ' The ancestors of this widget were:\n' + ' [root]\n' + ); + }); + + testWidgets('debugCheckHasMaterialLocalizations control test', ( + WidgetTester tester) async { + await tester.pumpWidget(const BackButton()); + final dynamic exception = tester.takeException(); + expect(exception, isFlutterError); + final FlutterError error = exception; + expect(error.diagnostics.length, 6); + expect(error.diagnostics[3].level, DiagnosticLevel.hint); + expect( + error.diagnostics[3].toStringDeep(), + equalsIgnoringHashCodes( + 'To introduce a MaterialLocalizations, either use a MaterialApp at\n' + 'the root of your application to include them automatically, or\n' + 'add a Localization widget with a MaterialLocalizations delegate.\n', + ), + ); + expect(error.diagnostics[4], isInstanceOf>()); + expect(error.diagnostics[5], isInstanceOf()); + expect(error.toStringDeep(), + 'FlutterError\n' + ' No MaterialLocalizations found.\n' + ' BackButton widgets require MaterialLocalizations to be provided\n' + ' by a Localizations widget ancestor.\n' + ' Localizations are used to generate many different messages,\n' + ' labels,and abbreviations which are used by the material library.\n' + ' To introduce a MaterialLocalizations, either use a MaterialApp at\n' + ' the root of your application to include them automatically, or\n' + ' add a Localization widget with a MaterialLocalizations delegate.\n' + ' The specific widget that could not find a MaterialLocalizations\n' + ' ancestor was:\n' + ' BackButton\n' + ' The ancestors of this widget were:\n' + ' [root]\n' + ); + }); + + testWidgets( + 'debugCheckHasScaffold control test', (WidgetTester tester) async { + await tester.pumpWidget( + MaterialApp( + home: Builder( + builder: (BuildContext context) { + showBottomSheet(context: context, + builder: (BuildContext context) => Container()); + return Container(); + } + ), + ), + ); + final dynamic exception = tester.takeException(); + expect(exception, isFlutterError); + final FlutterError error = exception; + expect(error.diagnostics.length, 5); + expect(error.diagnostics[2], isInstanceOf>()); + expect(error.diagnostics[3], isInstanceOf()); + expect(error.diagnostics[4].level, DiagnosticLevel.hint); + expect( + error.diagnostics[4].toStringDeep(), + equalsIgnoringHashCodes( + 'Typically, the Scaffold widget is introduced by the MaterialApp\n' + 'or WidgetsApp widget at the top of your application widget tree.\n', + ), + ); + expect(error.toStringDeep(), equalsIgnoringHashCodes( + 'FlutterError\n' + ' No Scaffold widget found.\n' + ' Builder widgets require a Scaffold widget ancestor.\n' + ' The specific widget that could not find a Scaffold ancestor was:\n' + ' Builder\n' + ' The ancestors of this widget were:\n' + ' Semantics\n' + ' Builder\n' + ' RepaintBoundary-[GlobalKey#2d465]\n' + ' IgnorePointer\n' + ' AnimatedBuilder\n' + ' FadeTransition\n' + ' FractionalTranslation\n' + ' SlideTransition\n' + ' _FadeUpwardsPageTransition\n' + ' AnimatedBuilder\n' + ' RepaintBoundary\n' + ' _FocusMarker\n' + ' Semantics\n' + ' FocusScope\n' + ' PageStorage\n' + ' Offstage\n' + ' _ModalScopeStatus\n' + ' _ModalScope-[LabeledGlobalKey<_ModalScopeState>#969b7]\n' + ' _OverlayEntry-[LabeledGlobalKey<_OverlayEntryState>#7a3ae]\n' + ' Stack\n' + ' _Theatre\n' + ' Overlay-[LabeledGlobalKey#31a52]\n' + ' _FocusMarker\n' + ' Semantics\n' + ' FocusScope\n' + ' AbsorbPointer\n' + ' _PointerListener\n' + ' Listener\n' + ' Navigator-[GlobalObjectKey _WidgetsAppState#10579]\n' + ' IconTheme\n' + ' IconTheme\n' + ' _InheritedCupertinoTheme\n' + ' CupertinoTheme\n' + ' _InheritedTheme\n' + ' Theme\n' + ' AnimatedTheme\n' + ' Builder\n' + ' DefaultTextStyle\n' + ' CustomPaint\n' + ' Banner\n' + ' CheckedModeBanner\n' + ' Title\n' + ' Directionality\n' + ' _LocalizationsScope-[GlobalKey#a51e3]\n' + ' Semantics\n' + ' Localizations\n' + ' MediaQuery\n' + ' _MediaQueryFromWindow\n' + ' DefaultFocusTraversal\n' + ' Actions\n' + ' _ShortcutsMarker\n' + ' Semantics\n' + ' _FocusMarker\n' + ' Focus\n' + ' Shortcuts\n' + ' WidgetsApp-[GlobalObjectKey _MaterialAppState#38e79]\n' + ' ScrollConfiguration\n' + ' MaterialApp\n' + ' [root]\n' + ' Typically, the Scaffold widget is introduced by the MaterialApp\n' + ' or WidgetsApp widget at the top of your application widget tree.\n', + )); }); } diff --git a/packages/flutter/test/material/page_test.dart b/packages/flutter/test/material/page_test.dart index 2c52ce394c..5295fb7282 100644 --- a/packages/flutter/test/material/page_test.dart +++ b/packages/flutter/test/material/page_test.dart @@ -468,7 +468,13 @@ void main() { )); await tester.pumpAndSettle(); // An exception should've been thrown because the `builder` returned null. - expect(tester.takeException(), isInstanceOf()); + final dynamic exception = tester.takeException(); + expect(exception, isInstanceOf()); + expect(exception.toStringDeep(), equalsIgnoringHashCodes( + 'FlutterError\n' + ' The builder for route "broken" returned null.\n' + ' Route builders must never return null.\n' + )); }); testWidgets('test iOS edge swipe then drop back at starting point works', (WidgetTester tester) async { diff --git a/packages/flutter/test/material/scaffold_test.dart b/packages/flutter/test/material/scaffold_test.dart index 181a1819af..4cbc53661d 100644 --- a/packages/flutter/test/material/scaffold_test.dart +++ b/packages/flutter/test/material/scaffold_test.dart @@ -3,10 +3,10 @@ // found in the LICENSE file. import 'package:flutter/foundation.dart'; +import 'package:flutter/gestures.dart' show DragStartBehavior; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; -import 'package:flutter/gestures.dart' show DragStartBehavior; import '../widgets/semantics_tester.dart'; @@ -1676,6 +1676,248 @@ void main() { await tester.pumpWidget(buildFrame(false, null)); expect(tester.getSize(find.byKey(bodyKey)), const Size(800.0, 500.0)); }); + + group('FlutterError control test', () { + testWidgets('showBottomSheet() while Scaffold has bottom sheet', + (WidgetTester tester) async { + final GlobalKey key = GlobalKey(); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + key: key, + body: Center( + child: Container(), + ), + bottomSheet: Container( + child: const Text('Bottom sheet'), + ), + ), + ), + ); + FlutterError error; + try { + key.currentState.showBottomSheet((BuildContext context) { + final ThemeData themeData = Theme.of(context); + return Container( + decoration: BoxDecoration( + border: Border(top: BorderSide(color: themeData.disabledColor)) + ), + child: Padding( + padding: const EdgeInsets.all(32.0), + child: Text('This is a Material persistent bottom sheet. Drag downwards to dismiss it.', + textAlign: TextAlign.center, + style: TextStyle( + color: themeData.accentColor, + fontSize: 24.0, + ), + ), + ), + ); + },); + } on FlutterError catch (e) { + error = e; + } finally { + expect(error, isNotNull); + expect(error.toStringDeep(), equalsIgnoringHashCodes( + 'FlutterError\n' + ' Scaffold.bottomSheet cannot be specified while a bottom\n' + ' sheetdisplayed with showBottomSheet() is still visible.\n' + ' Rebuild the Scaffold with a null bottomSheet before calling\n' + ' showBottomSheet().\n', + )); + } + } + ); + + testWidgets('didUpdate bottomSheet while a previous bottom sheet is still displayed', + (WidgetTester tester) async { + final GlobalKey key = GlobalKey(); + const Key buttonKey = Key('button'); + final List errors = []; + FlutterError.onError = (FlutterErrorDetails error) => errors.add(error); + int state = 0; + await tester.pumpWidget( + MaterialApp( + home: StatefulBuilder( + builder: (BuildContext context, StateSetter setState) { + return Scaffold( + key: key, + body: Container(), + floatingActionButton: FloatingActionButton( + key: buttonKey, + onPressed: () { + state += 1; + setState(() {}); + } + ), + bottomSheet: state == 0 ? null : const SizedBox(), + ); + } + ), + ), + ); + key.currentState.showBottomSheet((_) => Container()); + await tester.tap(find.byKey(buttonKey)); + await tester.pump(); + expect(errors, isNotEmpty); + expect(errors.first.exception, isFlutterError); + final FlutterError error = errors.first.exception; + expect(error.diagnostics.length, 2); + expect(error.diagnostics.last.level, DiagnosticLevel.hint); + expect( + error.diagnostics.last.toStringDeep(), + 'Use the PersistentBottomSheetController returned by\n' + 'showBottomSheet() to close the old bottom sheet before creating a\n' + 'Scaffold with a (non null) bottomSheet.\n', + ); + expect( + error.toStringDeep(), + 'FlutterError\n' + ' Scaffold.bottomSheet cannot be specified while a bottom sheet\n' + ' displayed with showBottomSheet() is still visible.\n' + ' Use the PersistentBottomSheetController returned by\n' + ' showBottomSheet() to close the old bottom sheet before creating a\n' + ' Scaffold with a (non null) bottomSheet.\n' + ); + }); + + testWidgets('Call to Scaffold.of() without context', (WidgetTester tester) async { + await tester.pumpWidget( + MaterialApp( + home: Builder( + builder: (BuildContext context) { + Scaffold.of(context).showBottomSheet((BuildContext context) { + return Container(); + }); + return Container(); + }, + ), + ), + ); + final dynamic exception = tester.takeException(); + expect(exception, isFlutterError); + final FlutterError error = exception; + expect(error.diagnostics.length, 5); + expect(error.diagnostics[2].level, DiagnosticLevel.hint); + expect( + error.diagnostics[2].toStringDeep(), + equalsIgnoringHashCodes( + 'There are several ways to avoid this problem. The simplest is to\n' + 'use a Builder to get a context that is "under" the Scaffold. For\n' + 'an example of this, please see the documentation for\n' + 'Scaffold.of():\n' + ' https://api.flutter.dev/flutter/material/Scaffold/of.html\n', + ), + ); + expect(error.diagnostics[3].level, DiagnosticLevel.hint); + expect( + error.diagnostics[3].toStringDeep(), + equalsIgnoringHashCodes( + 'A more efficient solution is to split your build function into\n' + 'several widgets. This introduces a new context from which you can\n' + 'obtain the Scaffold. In this solution, you would have an outer\n' + 'widget that creates the Scaffold populated by instances of your\n' + 'new inner widgets, and then in these inner widgets you would use\n' + 'Scaffold.of().\n' + 'A less elegant but more expedient solution is assign a GlobalKey\n' + 'to the Scaffold, then use the key.currentState property to obtain\n' + 'the ScaffoldState rather than using the Scaffold.of() function.\n', + ), + ); + expect(error.diagnostics[4], isInstanceOf>()); + expect(error.toStringDeep(), + 'FlutterError\n' + ' Scaffold.of() called with a context that does not contain a\n' + ' Scaffold.\n' + ' No Scaffold ancestor could be found starting from the context\n' + ' that was passed to Scaffold.of(). This usually happens when the\n' + ' context provided is from the same StatefulWidget as that whose\n' + ' build function actually creates the Scaffold widget being sought.\n' + ' There are several ways to avoid this problem. The simplest is to\n' + ' use a Builder to get a context that is "under" the Scaffold. For\n' + ' an example of this, please see the documentation for\n' + ' Scaffold.of():\n' + ' https://api.flutter.dev/flutter/material/Scaffold/of.html\n' + ' A more efficient solution is to split your build function into\n' + ' several widgets. This introduces a new context from which you can\n' + ' obtain the Scaffold. In this solution, you would have an outer\n' + ' widget that creates the Scaffold populated by instances of your\n' + ' new inner widgets, and then in these inner widgets you would use\n' + ' Scaffold.of().\n' + ' A less elegant but more expedient solution is assign a GlobalKey\n' + ' to the Scaffold, then use the key.currentState property to obtain\n' + ' the ScaffoldState rather than using the Scaffold.of() function.\n' + ' The context used was:\n' + ' Builder\n' + ); + await tester.pumpAndSettle(); + }); + + testWidgets('Call to Scaffold.geometryOf() without context', (WidgetTester tester) async { + ValueListenable geometry; + await tester.pumpWidget( + MaterialApp( + home: Builder( + builder: (BuildContext context) { + geometry = Scaffold.geometryOf(context); + return Container(); + }, + ), + ), + ); + final dynamic exception = tester.takeException(); + expect(exception, isFlutterError); + expect(geometry, isNull); + final FlutterError error = exception; + expect(error.diagnostics.length, 5); + expect(error.diagnostics[2].level, DiagnosticLevel.hint); + expect( + error.diagnostics[2].toStringDeep(), + equalsIgnoringHashCodes( + 'There are several ways to avoid this problem. The simplest is to\n' + 'use a Builder to get a context that is "under" the Scaffold. For\n' + 'an example of this, please see the documentation for\n' + 'Scaffold.of():\n' + ' https://api.flutter.dev/flutter/material/Scaffold/of.html\n', + ), + ); + expect(error.diagnostics[3].level, DiagnosticLevel.hint); + expect( + error.diagnostics[3].toStringDeep(), + equalsIgnoringHashCodes( + 'A more efficient solution is to split your build function into\n' + 'several widgets. This introduces a new context from which you can\n' + 'obtain the Scaffold. In this solution, you would have an outer\n' + 'widget that creates the Scaffold populated by instances of your\n' + 'new inner widgets, and then in these inner widgets you would use\n' + 'Scaffold.geometryOf().\n', + ), + ); + expect(error.diagnostics[4], isInstanceOf>()); + expect(error.toStringDeep(), + 'FlutterError\n' + ' Scaffold.geometryOf() called with a context that does not contain\n' + ' a Scaffold.\n' + ' This usually happens when the context provided is from the same\n' + ' StatefulWidget as that whose build function actually creates the\n' + ' Scaffold widget being sought.\n' + ' There are several ways to avoid this problem. The simplest is to\n' + ' use a Builder to get a context that is "under" the Scaffold. For\n' + ' an example of this, please see the documentation for\n' + ' Scaffold.of():\n' + ' https://api.flutter.dev/flutter/material/Scaffold/of.html\n' + ' A more efficient solution is to split your build function into\n' + ' several widgets. This introduces a new context from which you can\n' + ' obtain the Scaffold. In this solution, you would have an outer\n' + ' widget that creates the Scaffold populated by instances of your\n' + ' new inner widgets, and then in these inner widgets you would use\n' + ' Scaffold.geometryOf().\n' + ' The context used was:\n' + ' Builder\n' + ); + await tester.pumpAndSettle(); + }); + }); } class _GeometryListener extends StatefulWidget { diff --git a/packages/flutter/test/material/stepper_test.dart b/packages/flutter/test/material/stepper_test.dart index 1df4cce359..611b6f392a 100644 --- a/packages/flutter/test/material/stepper_test.dart +++ b/packages/flutter/test/material/stepper_test.dart @@ -529,14 +529,15 @@ void main() { // which will change depending on where the test is run. expect(lines.length, greaterThan(7)); expect( - lines.take(7).join('\n'), + lines.take(8).join('\n'), equalsIgnoringHashCodes( '══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞════════════════════════\n' 'The following assertion was thrown building Stepper(dirty,\n' 'dependencies: [_LocalizationsScope-[GlobalKey#00000]], state:\n' '_StepperState#00000):\n' - 'Steppers must not be nested. The material specification advises\n' - 'that one should avoid embedding steppers within steppers.\n' + 'Steppers must not be nested.\n' + 'The material specification advises that one should avoid\n' + 'embedding steppers within steppers.\n' 'https://material.io/archive/guidelines/components/steppers.html#steppers-usage' ), ); diff --git a/packages/flutter/test/material/text_field_test.dart b/packages/flutter/test/material/text_field_test.dart index d6582eba39..368690e2e4 100644 --- a/packages/flutter/test/material/text_field_test.dart +++ b/packages/flutter/test/material/text_field_test.dart @@ -3259,9 +3259,24 @@ void main() { expect(controller.selection.start, lessThanOrEqualTo(0)); expect(controller.selection.end, lessThanOrEqualTo(0)); - expect(() { + FlutterError error; + try { controller.selection = const TextSelection.collapsed(offset: 10); - }, throwsFlutterError); + } on FlutterError catch (e) { + error = e; + } finally { + expect(error, isNotNull); + expect(error.diagnostics.length, 1); + expect( + error.toStringDeep(), + equalsIgnoringHashCodes( + 'FlutterError\n' + ' invalid text selection: TextSelection(baseOffset: 10,\n' + ' extentOffset: 10, affinity: TextAffinity.downstream,\n' + ' isDirectional: false)\n', + ), + ); + } }); testWidgets('maxLength limits input.', (WidgetTester tester) async { diff --git a/packages/flutter/test/painting/border_rtl_test.dart b/packages/flutter/test/painting/border_rtl_test.dart index 2ae2de3cc5..4478bd94ce 100644 --- a/packages/flutter/test/painting/border_rtl_test.dart +++ b/packages/flutter/test/painting/border_rtl_test.dart @@ -2,10 +2,12 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +import 'package:flutter/foundation.dart' show DiagnosticLevel, FlutterError; import 'package:flutter/painting.dart'; import 'package:flutter_test/flutter_test.dart'; import '../rendering/mock_canvas.dart'; +import '../rendering/rendering_tester.dart'; class SillyBorder extends BoxBorder { @override @@ -115,6 +117,39 @@ void main() { expect(() => BoxBorder.lerp(SillyBorder(), const Border(), 2.0), throwsFlutterError); }); + test('BoxBorder.lerp throws correct FlutterError message', () { + FlutterError error; + try { + BoxBorder.lerp(SillyBorder(), const Border(), 2.0); + } on FlutterError catch (e) { + error = e; + } + expect(error, isNotNull); + expect(error.diagnostics.length, 3); + expect(error.diagnostics[2].level, DiagnosticLevel.hint); + expect( + error.diagnostics[2].toStringDeep(), + equalsIgnoringHashCodes( + 'For a more general interpolation method, consider using\n' + 'ShapeBorder.lerp instead.\n', + ), + ); + expect(error.toStringDeep(), equalsIgnoringHashCodes( + 'FlutterError\n' + ' BoxBorder.lerp can only interpolate Border and BorderDirectional\n' + ' classes.\n' + ' BoxBorder.lerp() was called with two objects of type SillyBorder\n' + ' and Border:\n' + ' SillyBorder()\n' + ' Border.all(BorderSide(Color(0xff000000), 0.0,\n' + ' BorderStyle.none))\n' + ' However, only Border and BorderDirectional classes are supported\n' + ' by this method.\n' + ' For a more general interpolation method, consider using\n' + ' ShapeBorder.lerp instead.\n' + )); + }); + test('BoxBorder.getInnerPath / BoxBorder.getOuterPath', () { // for Border, BorderDirectional const Border border = Border(top: BorderSide(width: 10.0), right: BorderSide(width: 20.0)); diff --git a/packages/flutter/test/painting/decoration_test.dart b/packages/flutter/test/painting/decoration_test.dart index 872a8ca68c..07429b2606 100644 --- a/packages/flutter/test/painting/decoration_test.dart +++ b/packages/flutter/test/painting/decoration_test.dart @@ -10,8 +10,8 @@ import 'dart:ui' as ui show Image, ImageByteFormat, ColorFilter; import 'package:flutter/foundation.dart'; import 'package:flutter/painting.dart'; import 'package:quiver/testing/async.dart'; -import '../flutter_test_alternative.dart'; +import '../flutter_test_alternative.dart'; import '../painting/mocks_for_image_cache.dart'; import '../rendering/rendering_tester.dart'; @@ -232,6 +232,43 @@ void main() { expect(call.positionalArguments[3].filterQuality, FilterQuality.low); }); + test( + 'DecorationImage with null textDirection configuration should throw Error', () { + final DecorationImage backgroundImage = DecorationImage( + image: SynchronousTestImageProvider(), + matchTextDirection: true, + ); + final BoxDecoration boxDecoration = BoxDecoration( + image: backgroundImage); + final BoxPainter boxPainter = boxDecoration.createBoxPainter(() { + assert(false); + }); + final TestCanvas canvas = TestCanvas([]); + FlutterError error; + try { + boxPainter.paint(canvas, Offset.zero, const ImageConfiguration( + size: Size(100.0, 100.0), textDirection: null)); + } on FlutterError catch (e) { + error = e; + } + expect(error, isNotNull); + expect(error.diagnostics.length, 4); + expect(error.diagnostics[2], isInstanceOf>()); + expect(error.diagnostics[3], isInstanceOf>()); + expect(error.toStringDeep(), + 'FlutterError\n' + ' ImageDecoration.matchTextDirection can only be used when a\n' + ' TextDirection is available.\n' + ' When DecorationImagePainter.paint() was called, there was no text\n' + ' direction provided in the ImageConfiguration object to match.\n' + ' The DecorationImage was:\n' + ' DecorationImage(SynchronousTestImageProvider(), center, match\n' + ' text direction)\n' + ' The ImageConfiguration was:\n' + ' ImageConfiguration(size: Size(100.0, 100.0))\n' + ); + }); + test('BoxDecoration.lerp - shapes', () { // We don't lerp the shape, we just switch from one to the other at t=0.5. // (Use a ShapeDecoration and ShapeBorder if you want to lerp the shapes...) diff --git a/packages/flutter/test/painting/text_span_test.dart b/packages/flutter/test/painting/text_span_test.dart index 963b65270a..cb65b66bf5 100644 --- a/packages/flutter/test/painting/text_span_test.dart +++ b/packages/flutter/test/painting/text_span_test.dart @@ -235,4 +235,29 @@ void main() { expect(textSpan.getSpanForPosition(const TextPosition(offset: 2)).runtimeType, WidgetSpan); expect(textSpan.getSpanForPosition(const TextPosition(offset: 3)).runtimeType, TextSpan); }); + + test('TextSpan with a null child should throw FlutterError', () { + const TextSpan text = TextSpan( + text: 'foo bar', + children: [ + null, + ], + ); + FlutterError error; + try { + text.computeToPlainText(StringBuffer()); + } on FlutterError catch (e) { + error = e; + } + expect(error, isNotNull); + expect(error.toStringDeep(), + 'FlutterError\n' + ' TextSpan contains a null child.\n' + ' A TextSpan object with a non-null child list should not have any\n' + ' nulls in its child list.\n' + ' The full text in question was:\n' + ' TextSpan("foo bar")\n' + ); + }); + } diff --git a/packages/flutter/test/rendering/aspect_ratio_test.dart b/packages/flutter/test/rendering/aspect_ratio_test.dart index d0e1c0f99a..b17e1dc782 100644 --- a/packages/flutter/test/rendering/aspect_ratio_test.dart +++ b/packages/flutter/test/rendering/aspect_ratio_test.dart @@ -108,14 +108,20 @@ void main() { ), ); - final List errorMessages = []; + final List errors = []; layout(box, onErrors: () { - errorMessages.addAll( - renderer.takeAllFlutterErrorDetails().map((FlutterErrorDetails details) => '${details.exceptionAsString()}'), - ); + errors.addAll(renderer.takeAllFlutterErrorDetails()); }); - expect(errorMessages, hasLength(2)); - expect(errorMessages[0], contains('RenderAspectRatio has unbounded constraints.')); + expect(errors, hasLength(2)); + expect(errors.first.exception, isA()); + expect(errors.first.exception.toStringDeep(), + 'FlutterError\n' + ' RenderAspectRatio has unbounded constraints.\n' + ' This RenderAspectRatio was given an aspect ratio of 0.5 but was\n' + ' given both unbounded width and unbounded height constraints.\n' + ' Because both constraints were unbounded, this render object\n' + ' doesn\'t know how much size to consume.\n' + ); // The second error message is a generic message generated by the Dart VM. Not worth testing. }); diff --git a/packages/flutter/test/rendering/debug_test.dart b/packages/flutter/test/rendering/debug_test.dart index 7d91514715..1eb702a7a1 100644 --- a/packages/flutter/test/rendering/debug_test.dart +++ b/packages/flutter/test/rendering/debug_test.dart @@ -151,7 +151,7 @@ void main() { ContainerLayer(), const Rect.fromLTRB(0.0, 0.0, 800.0, 600.0)), const Offset(0.0, 500), ); - } catch(e) { + } catch (e) { error = e; } expect(error, isNull); @@ -184,7 +184,7 @@ void main() { ContainerLayer(), const Rect.fromLTRB(0.0, 0.0, 800.0, 600.0)), const Offset(0.0, 500), ); - } catch(e) { + } catch (e) { error = e; } expect(error, isNull); diff --git a/packages/flutter/test/rendering/proxy_box_test.dart b/packages/flutter/test/rendering/proxy_box_test.dart index d6b8cc71c5..559c7eb449 100644 --- a/packages/flutter/test/rendering/proxy_box_test.dart +++ b/packages/flutter/test/rendering/proxy_box_test.dart @@ -531,6 +531,11 @@ class _FakeTicker implements Ticker { @override String toString({ bool debugIncludeStack = false }) => super.toString(); + + @override + DiagnosticsNode describeForError(String name) { + return DiagnosticsProperty(name, this, style: DiagnosticsTreeStyle.errorProperty); + } } // Forces two frames and checks that: diff --git a/packages/flutter/test/rendering/viewport_test.dart b/packages/flutter/test/rendering/viewport_test.dart index 8ee4b7e48f..2c437f317e 100644 --- a/packages/flutter/test/rendering/viewport_test.dart +++ b/packages/flutter/test/rendering/viewport_test.dart @@ -5,6 +5,7 @@ import 'dart:ui'; import 'package:flutter_test/flutter_test.dart'; +import 'package:flutter/foundation.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; @@ -979,4 +980,163 @@ void main() { await tester.pumpAndSettle(); expect(controller.offset, 300.0); }); + + group('unbounded constraints control test', () { + Widget buildNestedWidget([Axis a1 = Axis.vertical, Axis a2 = Axis.horizontal]) { + return Directionality( + textDirection: TextDirection.ltr, + child: Center( + child: Container( + child: ListView( + scrollDirection: a1, + children: List.generate(10, (int y) { + return Container( + child: ListView( + scrollDirection: a2, + ), + ); + }), + ), + ), + ), + ); + } + + Future expectFlutterError({ + Widget widget, + WidgetTester tester, + String message, + }) async { + final List errors = []; + final FlutterExceptionHandler oldHandler = FlutterError.onError; + FlutterError.onError = (FlutterErrorDetails error) => errors.add(error); + try { + await tester.pumpWidget(widget); + } finally { + FlutterError.onError = oldHandler; + } + expect(errors, isNotEmpty); + expect(errors.first.exception, isFlutterError); + expect(errors.first.exception.toStringDeep(), message); + } + + testWidgets('Horizontal viewport was given unbounded height', (WidgetTester tester) async { + await expectFlutterError( + widget: buildNestedWidget(), + tester: tester, + message: + 'FlutterError\n' + ' Horizontal viewport was given unbounded height.\n' + ' Viewports expand in the cross axis to fill their container and\n' + ' constrain their children to match their extent in the cross axis.\n' + ' In this case, a horizontal viewport was given an unlimited amount\n' + ' of vertical space in which to expand.\n', + ); + }); + + testWidgets('Horizontal viewport was given unbounded width', (WidgetTester tester) async { + await expectFlutterError( + widget: buildNestedWidget(Axis.horizontal, Axis.horizontal), + tester: tester, + message: + 'FlutterError\n' + ' Horizontal viewport was given unbounded width.\n' + ' Viewports expand in the scrolling direction to fill their\n' + ' container.In this case, a horizontal viewport was given an\n' + ' unlimited amount of horizontal space in which to expand. This\n' + ' situation typically happens when a scrollable widget is nested\n' + ' inside another scrollable widget.\n' + ' If this widget is always nested in a scrollable widget there is\n' + ' no need to use a viewport because there will always be enough\n' + ' horizontal space for the children. In this case, consider using a\n' + ' Row instead. Otherwise, consider using the "shrinkWrap" property\n' + ' (or a ShrinkWrappingViewport) to size the width of the viewport\n' + ' to the sum of the widths of its children.\n' + ); + }); + + testWidgets('Vertical viewport was given unbounded width', (WidgetTester tester) async { + await expectFlutterError( + widget: buildNestedWidget(Axis.horizontal, Axis.vertical), + tester: tester, + message: + 'FlutterError\n' + ' Vertical viewport was given unbounded width.\n' + ' Viewports expand in the cross axis to fill their container and\n' + ' constrain their children to match their extent in the cross axis.\n' + ' In this case, a vertical viewport was given an unlimited amount\n' + ' of horizontal space in which to expand.\n' + ); + }); + + testWidgets('Vertical viewport was given unbounded height', (WidgetTester tester) async { + await expectFlutterError( + widget: buildNestedWidget(Axis.vertical, Axis.vertical), + tester: tester, + message: + 'FlutterError\n' + ' Vertical viewport was given unbounded height.\n' + ' Viewports expand in the scrolling direction to fill their\n' + ' container. In this case, a vertical viewport was given an\n' + ' unlimited amount of vertical space in which to expand. This\n' + ' situation typically happens when a scrollable widget is nested\n' + ' inside another scrollable widget.\n' + ' If this widget is always nested in a scrollable widget there is\n' + ' no need to use a viewport because there will always be enough\n' + ' vertical space for the children. In this case, consider using a\n' + ' Column instead. Otherwise, consider using the "shrinkWrap"\n' + ' property (or a ShrinkWrappingViewport) to size the height of the\n' + ' viewport to the sum of the heights of its children.\n' + ); + }); + }); + + test('Viewport debugThrowIfNotCheckingIntrinsics() control test', () { + final RenderViewport renderViewport = RenderViewport( + crossAxisDirection: AxisDirection.right, offset: ViewportOffset.zero() + ); + FlutterError error; + try { + renderViewport.computeMinIntrinsicHeight(0); + } on FlutterError catch (e) { + error = e; + } + expect(error, isNotNull); + expect( + error.toStringDeep(), + 'FlutterError\n' + ' RenderViewport does not support returning intrinsic dimensions.\n' + ' Calculating the intrinsic dimensions would require instantiating\n' + ' every child of the viewport, which defeats the point of viewports\n' + ' being lazy.\n' + ' If you are merely trying to shrink-wrap the viewport in the main\n' + ' axis direction, consider a RenderShrinkWrappingViewport render\n' + ' object (ShrinkWrappingViewport widget), which achieves that\n' + ' effect without implementing the intrinsic dimension API.\n', + ); + + final RenderShrinkWrappingViewport renderShrinkWrappingViewport = RenderShrinkWrappingViewport( + crossAxisDirection: AxisDirection.right, offset: ViewportOffset.zero() + ); + error = null; + try { + renderShrinkWrappingViewport.computeMinIntrinsicHeight(0); + } on FlutterError catch (e) { + error = e; + } + expect(error, isNotNull); + expect( + error.toStringDeep(), + 'FlutterError\n' + ' RenderShrinkWrappingViewport does not support returning intrinsic\n' + ' dimensions.\n' + ' Calculating the intrinsic dimensions would require instantiating\n' + ' every child of the viewport, which defeats the point of viewports\n' + ' being lazy.\n' + ' If you are merely trying to shrink-wrap the viewport in the main\n' + ' axis direction, you should be able to achieve that effect by just\n' + ' giving the viewport loose constraints, without needing to measure\n' + ' its intrinsic dimensions.\n', + ); + }); } diff --git a/packages/flutter/test/scheduler/ticker_test.dart b/packages/flutter/test/scheduler/ticker_test.dart index 0aa3cd3b70..c65bd9936c 100644 --- a/packages/flutter/test/scheduler/ticker_test.dart +++ b/packages/flutter/test/scheduler/ticker_test.dart @@ -2,6 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +import 'package:flutter/foundation.dart'; import 'package:flutter/scheduler.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; @@ -24,7 +25,26 @@ void main() { expect(ticker.isActive, isTrue); expect(tickCount, equals(0)); - expect(ticker.start, throwsFlutterError); + FlutterError error; + try { + ticker.start(); + } on FlutterError catch (e) { + error = e; + } + expect(error, isNotNull); + expect(error.diagnostics.length, 3); + expect(error.diagnostics.last, isInstanceOf>()); + expect( + error.toStringDeep(), + startsWith( + 'FlutterError\n' + ' A ticker was started twice.\n' + ' A ticker that is already active cannot be started again without\n' + ' first stopping it.\n' + ' The affected ticker was:\n' + ' Ticker()\n', + ), + ); await tester.pump(const Duration(milliseconds: 10)); diff --git a/packages/flutter/test/services/asset_bundle_test.dart b/packages/flutter/test/services/asset_bundle_test.dart index a11163a680..08dc579572 100644 --- a/packages/flutter/test/services/asset_bundle_test.dart +++ b/packages/flutter/test/services/asset_bundle_test.dart @@ -56,4 +56,24 @@ void main() { expect(key.name, 'one'); expect(key.scale, 1.0); }); + + test('NetworkAssetBundle control test', () async { + final Uri uri = Uri.http('example.org', '/path'); + final NetworkAssetBundle bundle = NetworkAssetBundle(uri); + FlutterError error; + try { + await bundle.load('key'); + } on FlutterError catch (e) { + error = e; + } + expect(error, isNotNull); + expect(error.diagnostics.length, 2); + expect(error.diagnostics.last, isInstanceOf()); + expect( + error.toStringDeep(), + 'FlutterError\n' + ' Unable to load asset: key\n' + ' HTTP status code: 404\n', + ); + }, skip: true); } diff --git a/packages/flutter/test/widgets/animated_list_test.dart b/packages/flutter/test/widgets/animated_list_test.dart index 9553b1bb17..f0b15349ce 100644 --- a/packages/flutter/test/widgets/animated_list_test.dart +++ b/packages/flutter/test/widgets/animated_list_test.dart @@ -3,6 +3,7 @@ // found in the LICENSE file. import 'package:flutter_test/flutter_test.dart'; +import 'package:flutter/src/foundation/diagnostics.dart'; import 'package:flutter/widgets.dart'; void main() { @@ -319,4 +320,47 @@ void main() { expect(tester.getTopLeft(find.text('item 0')).dy, 200); }); }); + + testWidgets('AnimatedList.of() called with a context that does not contain AnimatedList', + (WidgetTester tester) async { + final GlobalKey key = GlobalKey(); + await tester.pumpWidget(Container(key: key)); + FlutterError error; + try { + AnimatedList.of(key.currentContext); + } on FlutterError catch (e) { + error = e; + } + expect(error, isNotNull); + expect(error.diagnostics.length, 4); + expect(error.diagnostics[2].level, DiagnosticLevel.hint); + expect( + error.diagnostics[2].toStringDeep(), + equalsIgnoringHashCodes( + 'This can happen when the context provided is from the same\n' + 'StatefulWidget that built the AnimatedList. Please see the\n' + 'AnimatedList documentation for examples of how to refer to an\n' + 'AnimatedListState object:\n' + 'https://api.flutter.dev/flutter/widgets/AnimatedListState-class.html\n' + ), + ); + expect(error.diagnostics[3], isInstanceOf>()); + expect( + error.toStringDeep(), + equalsIgnoringHashCodes( + 'FlutterError\n' + ' AnimatedList.of() called with a context that does not contain an\n' + ' AnimatedList.\n' + ' No AnimatedList ancestor could be found starting from the context\n' + ' that was passed to AnimatedList.of().\n' + ' This can happen when the context provided is from the same\n' + ' StatefulWidget that built the AnimatedList. Please see the\n' + ' AnimatedList documentation for examples of how to refer to an\n' + ' AnimatedListState object:\n' + ' https://api.flutter.dev/flutter/widgets/AnimatedListState-class.html\n' + ' The context used was:\n' + ' Container-[GlobalKey#32cc6]\n' + ), + ); + }); } diff --git a/packages/flutter/test/widgets/app_test.dart b/packages/flutter/test/widgets/app_test.dart index 03c337da09..8011e879c7 100644 --- a/packages/flutter/test/widgets/app_test.dart +++ b/packages/flutter/test/widgets/app_test.dart @@ -2,6 +2,7 @@ // 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:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; @@ -19,4 +20,72 @@ void main() { ); expect(find.byKey(key), findsOneWidget); }); + + group('error control test', () { + Future expectFlutterError({ + GlobalKey key, + Widget widget, + WidgetTester tester, + String errorMessage, + }) async { + await tester.pumpWidget(widget); + FlutterError error; + try { + key.currentState.pushNamed('/path'); + } on FlutterError catch (e) { + error = e; + } finally { + expect(error, isNotNull); + expect(error, isFlutterError); + expect(error.toStringDeep(), errorMessage); + } + } + + testWidgets('push unknown route when onUnknownRoute is null', (WidgetTester tester) async { + final GlobalKey key = GlobalKey(); + expectFlutterError( + key: key, + tester: tester, + widget: MaterialApp( + navigatorKey: key, + home: Container(), + onGenerateRoute: (_) => null, + ), + errorMessage: + 'FlutterError\n' + ' Could not find a generator for route RouteSettings("/path", null)\n' + ' in the _WidgetsAppState.\n' + ' Generators for routes are searched for in the following order:\n' + ' 1. For the "/" route, the "home" property, if non-null, is used.\n' + ' 2. Otherwise, the "routes" table is used, if it has an entry for\n' + ' the route.\n' + ' 3. Otherwise, onGenerateRoute is called. It should return a\n' + ' non-null value for any valid route not handled by "home" and\n' + ' "routes".\n' + ' 4. Finally if all else fails onUnknownRoute is called.\n' + ' Unfortunately, onUnknownRoute was not set.\n', + ); + }); + + testWidgets('push unknown route when onUnknownRoute returns null', (WidgetTester tester) async { + final GlobalKey key = GlobalKey(); + expectFlutterError( + key: key, + tester: tester, + widget: MaterialApp( + navigatorKey: key, + home: Container(), + onGenerateRoute: (_) => null, + onUnknownRoute: (_) => null, + ), + errorMessage: + 'FlutterError\n' + ' The onUnknownRoute callback returned null.\n' + ' When the _WidgetsAppState requested the route\n' + ' RouteSettings("/path", null) from its onUnknownRoute callback,\n' + ' the callback returned null. Such callbacks must never return\n' + ' null.\n' , + ); + }); + }); } diff --git a/packages/flutter/test/widgets/binding_test.dart b/packages/flutter/test/widgets/binding_test.dart index e1ed3f647f..31695e25ee 100644 --- a/packages/flutter/test/widgets/binding_test.dart +++ b/packages/flutter/test/widgets/binding_test.dart @@ -138,4 +138,36 @@ void main() { expect(tester.binding.hasScheduledFrame, isFalse); expect(frameCount, 1); }); + + testWidgets('scheduleFrameCallback error control test', (WidgetTester tester) async { + FlutterError error; + try { + tester.binding.scheduleFrameCallback(null, rescheduling: true); + } on FlutterError catch (e) { + error = e; + } + expect(error, isNotNull); + expect(error.diagnostics.length, 3); + expect(error.diagnostics.last.level, DiagnosticLevel.hint); + expect( + error.diagnostics.last.toStringDeep(), + equalsIgnoringHashCodes( + 'If this is the initial registration of the callback, or if the\n' + 'callback is asynchronous, then do not use the "rescheduling"\n' + 'argument.\n' + ), + ); + expect( + error.toStringDeep(), + 'FlutterError\n' + ' scheduleFrameCallback called with rescheduling true, but no\n' + ' callback is in scope.\n' + ' The "rescheduling" argument should only be set to true if the\n' + ' callback is being reregistered from within the callback itself,\n' + ' and only then if the callback itself is entirely synchronous.\n' + ' If this is the initial registration of the callback, or if the\n' + ' callback is asynchronous, then do not use the "rescheduling"\n' + ' argument.\n' + ); + }); } diff --git a/packages/flutter/test/widgets/container_test.dart b/packages/flutter/test/widgets/container_test.dart index 9eb9cf22da..b007ec8c10 100644 --- a/packages/flutter/test/widgets/container_test.dart +++ b/packages/flutter/test/widgets/container_test.dart @@ -4,6 +4,7 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:flutter/widgets.dart'; +import 'package:mockito/mockito.dart'; import '../rendering/mock_canvas.dart'; @@ -461,6 +462,32 @@ void main() { ' android)\n', ), ); + + final RenderBox decoratedBox = tester.renderObject(find.byType(DecoratedBox).last); + final PaintingContext context = _MockPaintingContext(); + final Canvas canvas = _MockCanvas(); + int saveCount = 0; + when(canvas.getSaveCount()).thenAnswer((_) => saveCount++); + when(context.canvas).thenReturn(canvas); + FlutterError error; + try { + decoratedBox.paint(context, const Offset(0, 0)); + } on FlutterError catch (e) { + error = e; + } + expect(error, isNotNull); + expect( + error.toStringDeep(), + 'FlutterError\n' + ' BoxDecoration painter had mismatching save and restore calls.\n' + ' Before painting the decoration, the canvas save count was 0.\n' + ' After painting it, the canvas save count was 2. Every call to\n' + ' save() or saveLayer() must be matched by a call to restore().\n' + ' The decoration was:\n' + ' BoxDecoration(color: Color(0xffffff00))\n' + ' The painter was:\n' + ' BoxPainter for BoxDecoration(color: Color(0xffffff00))\n' + ); }); testWidgets('Can be placed in an infinite box', (WidgetTester tester) async { @@ -472,3 +499,6 @@ void main() { ); }); } + +class _MockPaintingContext extends Mock implements PaintingContext {} +class _MockCanvas extends Mock implements Canvas {} diff --git a/packages/flutter/test/widgets/custom_multi_child_layout_test.dart b/packages/flutter/test/widgets/custom_multi_child_layout_test.dart index b0fe19fb27..6d0b6a24d4 100644 --- a/packages/flutter/test/widgets/custom_multi_child_layout_test.dart +++ b/packages/flutter/test/widgets/custom_multi_child_layout_test.dart @@ -3,6 +3,7 @@ // found in the LICENSE file. import 'package:flutter_test/flutter_test.dart'; +import 'package:flutter/foundation.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; @@ -90,6 +91,86 @@ class NotifierLayoutDelegate extends MultiChildLayoutDelegate { } } +// LayoutDelegate that lays out child with id 0 and 1 +// Used in the 'performLayout error control test' test case to trigger: +// - error when laying out a non existent child and a child that has not been laid out +class ZeroAndOneIdLayoutDelegate extends MultiChildLayoutDelegate { + @override + void performLayout(Size size) { + final BoxConstraints constraints = BoxConstraints.loose(size); + layoutChild(0, constraints); + layoutChild(1, constraints); + } + + @override + bool shouldRelayout(MultiChildLayoutDelegate oldDelegate) => true; +} + +// Used in the 'performLayout error control test' test case +// to trigger an error when laying out child more than once +class DuplicateLayoutDelegate extends MultiChildLayoutDelegate { + @override + void performLayout(Size size) { + final BoxConstraints constraints = BoxConstraints.loose(size); + layoutChild(0, constraints); + layoutChild(0, constraints); + } + + @override + bool shouldRelayout(MultiChildLayoutDelegate oldDelegate) => true; +} +// Used in the 'performLayout error control test' test case +// to trigger an error when positioning non existent child +class NonExistentPositionDelegate extends MultiChildLayoutDelegate { + @override + void performLayout(Size size) { + positionChild(0, const Offset(0, 0)); + positionChild(1, const Offset(0, 0)); + } + + @override + bool shouldRelayout(MultiChildLayoutDelegate oldDelegate) => true; +} + +// Used in the 'performLayout error control test' test case +// to trigger an error when positioning with null offset +class NullOffsetPositionDelegate extends MultiChildLayoutDelegate { + @override + void performLayout(Size size) { + positionChild(0, null); + } + + @override + bool shouldRelayout(MultiChildLayoutDelegate oldDelegate) => true; +} + +// Used in the 'performLayout error control test' test case for triggering +// to layout child more than once +class InvalidConstraintsChildLayoutDelegate extends MultiChildLayoutDelegate { + @override + void performLayout(Size size) { + final BoxConstraints constraints = BoxConstraints.loose( + // Invalid because width and height must be greater than or equal to 0 + const Size(-1, -1) + ); + layoutChild(0, constraints); + } + + @override + bool shouldRelayout(MultiChildLayoutDelegate oldDelegate) => true; +} + +class LayoutWithMissingId extends ParentDataWidget { + const LayoutWithMissingId({ + Key key, + @required Widget child, + }) : assert(child != null), + super(key: key, child: child); + + @override + void applyParentData(RenderObject renderObject) {} +} + void main() { testWidgets('Control test for CustomMultiChildLayout', (WidgetTester tester) async { final TestMultiChildLayoutDelegate delegate = TestMultiChildLayoutDelegate(); @@ -199,4 +280,170 @@ void main() { box = tester.renderObject(find.byType(CustomMultiChildLayout)); expect(box.size, equals(const Size(150.0, 240.0))); }); + + group('performLayout error control test', () { + Widget buildSingleChildFrame(MultiChildLayoutDelegate delegate) { + return Center( + child: CustomMultiChildLayout( + children: [LayoutId(id: 0, child: const SizedBox())], + delegate: delegate, + ), + ); + } + + Future expectFlutterErrorMessage({ + Widget widget, + MultiChildLayoutDelegate delegate, + @required WidgetTester tester, + @required String message, + }) async { + final FlutterExceptionHandler oldHandler = FlutterError.onError; + final List errors = []; + FlutterError.onError = (FlutterErrorDetails error) => errors.add(error); + try { + await tester.pumpWidget(widget ?? buildSingleChildFrame(delegate)); + } finally { + FlutterError.onError = oldHandler; + } + expect(errors.length, isNonZero); + expect(errors.first, isNotNull); + expect(errors.first.exception, isFlutterError); + expect(errors.first.exception.toStringDeep(), equalsIgnoringHashCodes(message)); + } + + testWidgets('layoutChild on non existent child', (WidgetTester tester) async { + expectFlutterErrorMessage( + tester: tester, + delegate: ZeroAndOneIdLayoutDelegate(), + message: + 'FlutterError\n' + ' The ZeroAndOneIdLayoutDelegate custom multichild layout delegate\n' + ' tried to lay out a non-existent child.\n' + ' There is no child with the id "1".\n' + ); + }); + + testWidgets('layoutChild more than once', (WidgetTester tester) async { + expectFlutterErrorMessage( + tester: tester, + delegate: DuplicateLayoutDelegate(), + message: + 'FlutterError\n' + ' The DuplicateLayoutDelegate custom multichild layout delegate\n' + ' tried to lay out the child with id "0" more than once.\n' + ' Each child must be laid out exactly once.\n' + ); + }); + + testWidgets('layoutChild on invalid size constraint', (WidgetTester tester) async { + expectFlutterErrorMessage( + tester: tester, + delegate: InvalidConstraintsChildLayoutDelegate(), + message: + 'FlutterError\n' + ' The InvalidConstraintsChildLayoutDelegate custom multichild\n' + ' layout delegate provided invalid box constraints for the child\n' + ' with id "0".\n' + ' FlutterError\n' + ' The minimum width and height must be greater than or equal to\n' + ' zero.\n' + ' The maximum width must be greater than or equal to the minimum\n' + ' width.\n' + ' The maximum height must be greater than or equal to the minimum\n' + ' height.\n' + ); + }); + + testWidgets('positionChild on non existent child', (WidgetTester tester) async { + expectFlutterErrorMessage( + tester: tester, + delegate: NonExistentPositionDelegate(), + message: + 'FlutterError\n' + ' The NonExistentPositionDelegate custom multichild layout delegate\n' + ' tried to position out a non-existent child:\n' + ' There is no child with the id "1".\n' + ); + }); + + testWidgets('positionChild on non existent child', (WidgetTester tester) async { + expectFlutterErrorMessage( + tester: tester, + delegate: NullOffsetPositionDelegate(), + message: + 'FlutterError\n' + ' The NullOffsetPositionDelegate custom multichild layout delegate\n' + ' provided a null position for the child with id "0".\n', + ); + }); + + testWidgets("_callPerformLayout on child that doesn't have id", (WidgetTester tester) async { + expectFlutterErrorMessage( + widget: Center( + child: CustomMultiChildLayout( + children: [LayoutWithMissingId(child: Container(width: 100))], + delegate: PreferredSizeDelegate(preferredSize: const Size(10, 10)), + ), + ), + tester: tester, + message: + 'FlutterError\n' + ' Every child of a RenderCustomMultiChildLayoutBox must have an ID\n' + ' in its parent data.\n' + ' The following child has no ID: RenderConstrainedBox#00000 NEEDS-LAYOUT NEEDS-PAINT:\n' + ' creator: ConstrainedBox ← Container ← LayoutWithMissingId ←\n' + ' CustomMultiChildLayout ← Center ← [root]\n' + ' parentData: offset=Offset(0.0, 0.0); id=null\n' + ' constraints: MISSING\n' + ' size: MISSING\n' + ' additionalConstraints: BoxConstraints(w=100.0, 0.0<=h<=Infinity)\n' + ); + }); + + testWidgets('performLayout did not layout a child', (WidgetTester tester) async { + expectFlutterErrorMessage( + widget: Center( + child: CustomMultiChildLayout( + children: [ + LayoutId(id: 0, child: Container(width: 100)), + LayoutId(id: 1, child: Container(width: 100)), + LayoutId(id: 2, child: Container(width: 100)), + ], + delegate: ZeroAndOneIdLayoutDelegate(), + ), + ), + tester: tester, + message: + 'FlutterError\n' + ' Each child must be laid out exactly once.\n' + ' The ZeroAndOneIdLayoutDelegate custom multichild layout delegate' + ' forgot to lay out the following child:\n' + ' 2: RenderConstrainedBox#62a34 NEEDS-LAYOUT NEEDS-PAINT\n' + ); + }); + + testWidgets('performLayout did not layout multiple child', (WidgetTester tester) async { + expectFlutterErrorMessage( + widget: Center( + child: CustomMultiChildLayout( + children: [ + LayoutId(id: 0, child: Container(width: 100)), + LayoutId(id: 1, child: Container(width: 100)), + LayoutId(id: 2, child: Container(width: 100)), + LayoutId(id: 3, child: Container(width: 100)), + ], + delegate: ZeroAndOneIdLayoutDelegate(), + ), + ), + tester: tester, + message: + 'FlutterError\n' + ' Each child must be laid out exactly once.\n' + ' The ZeroAndOneIdLayoutDelegate custom multichild layout delegate' + ' forgot to lay out the following children:\n' + ' 2: RenderConstrainedBox#62a34 NEEDS-LAYOUT NEEDS-PAINT\n' + ' 3: RenderConstrainedBox#62a34 NEEDS-LAYOUT NEEDS-PAINT\n' + ); + }); + }); } diff --git a/packages/flutter/test/widgets/custom_paint_test.dart b/packages/flutter/test/widgets/custom_paint_test.dart index 26e5859cd3..a9f938fe83 100644 --- a/packages/flutter/test/widgets/custom_paint_test.dart +++ b/packages/flutter/test/widgets/custom_paint_test.dart @@ -2,9 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import 'package:flutter_test/flutter_test.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mockito/mockito.dart'; class TestCustomPainter extends CustomPainter { TestCustomPainter({ this.log, this.name }); @@ -21,6 +22,25 @@ class TestCustomPainter extends CustomPainter { bool shouldRepaint(TestCustomPainter oldPainter) => true; } +class TestCustomPainterWithCustomSemanticsBuilder extends TestCustomPainter { + TestCustomPainterWithCustomSemanticsBuilder() : super(log: []); + + @override + SemanticsBuilderCallback get semanticsBuilder => (Size size) { + const Key key = Key('0'); + const Rect rect = Rect.fromLTRB(0, 0, 0, 0); + const SemanticsProperties semanticsProperties = SemanticsProperties(); + return [ + const CustomPainterSemantics(key: key, rect: rect, properties: semanticsProperties), + const CustomPainterSemantics(key: key, rect: rect, properties: semanticsProperties), + ]; + }; +} + +class MockCanvas extends Mock implements Canvas {} + +class MockPaintingContext extends Mock implements PaintingContext {} + void main() { testWidgets('Control test for custom painting', (WidgetTester tester) async { final List log = []; @@ -44,6 +64,108 @@ void main() { expect(log, equals(['background', 'child', 'foreground'])); }); + testWidgets('Throws FlutterError on custom painter incorrect restore/save calls', ( + WidgetTester tester) async { + final GlobalKey target = GlobalKey(); + final List log = []; + await tester.pumpWidget(CustomPaint( + key: target, + isComplex: true, + painter: TestCustomPainter(log: log), + )); + final RenderCustomPaint renderCustom = target.currentContext.findRenderObject(); + final Canvas canvas = MockCanvas(); + int saveCount = 0; + when(canvas.getSaveCount()).thenAnswer((_) => saveCount++); + final PaintingContext paintingContext = MockPaintingContext(); + when(paintingContext.canvas).thenReturn(canvas); + + FlutterError getError() { + FlutterError error; + try { + renderCustom.paint(paintingContext, const Offset(0, 0)); + } on FlutterError catch (e) { + error = e; + } + return error; + } + + FlutterError error = getError(); + expect(error.toStringDeep(), equalsIgnoringHashCodes( + 'FlutterError\n' + ' The TestCustomPainter#00000() custom painter called canvas.save()\n' + ' or canvas.saveLayer() at least 1 more time than it called\n' + ' canvas.restore().\n' + ' This leaves the canvas in an inconsistent state and will probably\n' + ' result in a broken display.\n' + ' You must pair each call to save()/saveLayer() with a later\n' + ' matching call to restore().\n' + )); + + when(canvas.getSaveCount()).thenAnswer((_) => saveCount--); + error = getError(); + expect(error.toStringDeep(), equalsIgnoringHashCodes( + 'FlutterError\n' + ' The TestCustomPainter#00000() custom painter called\n' + ' canvas.restore() 1 more time than it called canvas.save() or\n' + ' canvas.saveLayer().\n' + ' This leaves the canvas in an inconsistent state and will result\n' + ' in a broken display.\n' + ' You should only call restore() if you first called save() or\n' + ' saveLayer().\n' + )); + + when(canvas.getSaveCount()).thenAnswer((_) => saveCount += 2); + error = getError(); + expect(error.toStringDeep(), contains('2 more times')); + + when(canvas.getSaveCount()).thenAnswer((_) => saveCount -= 2); + error = getError(); + expect(error.toStringDeep(), contains('2 more times')); + }); + + testWidgets('assembleSemanticsNode throws FlutterError', (WidgetTester tester) async { + final List log = []; + final GlobalKey target = GlobalKey(); + await tester.pumpWidget(CustomPaint( + key: target, + isComplex: true, + painter: TestCustomPainter(log: log), + )); + final RenderCustomPaint renderCustom = target.currentContext.findRenderObject(); + FlutterError error; + try { + renderCustom.assembleSemanticsNode( + null, + null, + [SemanticsNode()], + ); + } on FlutterError catch (e) { + error = e; + } + expect(error, isNotNull); + expect(error.toStringDeep(), equalsIgnoringHashCodes( + 'FlutterError\n' + ' RenderCustomPaint does not have a child widget but received a\n' + ' non-empty list of child SemanticsNode:\n' + ' SemanticsNode#1(Rect.fromLTRB(0.0, 0.0, 0.0, 0.0), invisible)\n' + )); + + await tester.pumpWidget(CustomPaint( + key: target, + isComplex: true, + painter: TestCustomPainterWithCustomSemanticsBuilder(), + )); + final dynamic exception = tester.takeException(); + expect(exception, isFlutterError); + error = exception; + expect(error.toStringDeep(), equalsIgnoringHashCodes( + 'FlutterError\n' + ' Failed to update the list of CustomPainterSemantics:\n' + ' - duplicate key [<\'0\'>] found at position 1\n' + )); + }); + testWidgets('CustomPaint sizing', (WidgetTester tester) async { final GlobalKey target = GlobalKey(); diff --git a/packages/flutter/test/widgets/debug_test.dart b/packages/flutter/test/widgets/debug_test.dart new file mode 100644 index 0000000000..0be93b7a63 --- /dev/null +++ b/packages/flutter/test/widgets/debug_test.dart @@ -0,0 +1,235 @@ +// Copyright 2019 The Chromium Authors. 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/foundation.dart'; +import 'package:flutter/widgets.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + test('debugChildrenHaveDuplicateKeys control test', () { + const Key key = Key('key'); + final List children = [ + Container(key: key), + Container(key: key), + ]; + final Widget widget = Flex( + direction: Axis.vertical, + children: children + ); + FlutterError error; + try { + debugChildrenHaveDuplicateKeys(widget, children); + } on FlutterError catch (e) { + error = e; + } finally { + expect(error, isNotNull); + expect( + error.toStringDeep(), + equalsIgnoringHashCodes( + 'FlutterError\n' + ' Duplicate keys found.\n' + ' If multiple keyed nodes exist as children of another node, they\n' + ' must have unique keys.\n' + ' Flex(direction: vertical, mainAxisAlignment: start,\n' + ' crossAxisAlignment: center) has multiple children with key\n' + ' [<\'key\'>].\n', + ), + ); + } + }); + + test('debugItemsHaveDuplicateKeys control test', () { + const Key key = Key('key'); + final List items = [ + Container(key: key), + Container(key: key), + ]; + FlutterError error; + try { + debugItemsHaveDuplicateKeys(items); + } on FlutterError catch (e) { + error = e; + } finally { + expect(error, isNotNull); + expect( + error.toStringDeep(), + equalsIgnoringHashCodes( + 'FlutterError\n' + ' Duplicate key found: [<\'key\'>].\n' + ), + ); + } + }); + + testWidgets('debugCheckHasTable control test', (WidgetTester tester) async { + await tester.pumpWidget( + Builder( + builder: (BuildContext context) { + FlutterError error; + try { + debugCheckHasTable(context); + } on FlutterError catch (e) { + error = e; + } finally { + expect(error, isNotNull); + expect(error.diagnostics.length, 4); + expect(error.diagnostics[2], isInstanceOf>()); + expect( + error.toStringDeep(), + equalsIgnoringHashCodes( + 'FlutterError\n' + ' No Table widget found.\n' + ' Builder widgets require a Table widget ancestor.\n' + ' The specific widget that could not find a Table ancestor was:\n' + ' Builder\n' + ' The ownership chain for the affected widget is: "Builder ←\n' + ' [root]"\n' + ), + ); + } + return Container(); + } + ), + ); + }); + + testWidgets('debugCheckHasMediaQuery control test', (WidgetTester tester) async { + await tester.pumpWidget( + Builder( + builder: (BuildContext context) { + FlutterError error; + try { + debugCheckHasMediaQuery(context); + } on FlutterError catch (e) { + error = e; + } finally { + expect(error, isNotNull); + expect(error.diagnostics.length, 5); + expect(error.diagnostics[2], isInstanceOf>()); + expect(error.diagnostics.last.level, DiagnosticLevel.hint); + expect( + error.diagnostics.last.toStringDeep(), + equalsIgnoringHashCodes( + 'Typically, the MediaQuery widget is introduced by the MaterialApp\n' + 'or WidgetsApp widget at the top of your application widget tree.\n' + ), + ); + expect( + error.toStringDeep(), + equalsIgnoringHashCodes( + 'FlutterError\n' + ' No MediaQuery widget found.\n' + ' Builder widgets require a MediaQuery widget ancestor.\n' + ' The specific widget that could not find a MediaQuery ancestor\n' + ' was:\n' + ' Builder\n' + ' The ownership chain for the affected widget is: "Builder ←\n' + ' [root]"\n' + ' Typically, the MediaQuery widget is introduced by the MaterialApp\n' + ' or WidgetsApp widget at the top of your application widget tree.\n' + ), + ); + } + return Container(); + } + ), + ); + }); + + test('debugWidgetBuilderValue control test', () { + final Widget widget = Container(); + FlutterError error; + try { + debugWidgetBuilderValue(widget, null); + } on FlutterError catch (e) { + error = e; + } finally { + expect(error, isNotNull); + expect(error.diagnostics.length, 4); + expect(error.diagnostics[1], isInstanceOf>()); + expect(error.diagnostics[1].style, DiagnosticsTreeStyle.errorProperty); + expect( + error.diagnostics[1].toStringDeep(), + equalsIgnoringHashCodes( + 'The offending widget is:\n' + ' Container\n' + ) + ); + expect(error.diagnostics[2].level, DiagnosticLevel.info); + expect(error.diagnostics[3].level, DiagnosticLevel.hint); + expect( + error.diagnostics[3].toStringDeep(), + equalsIgnoringHashCodes( + 'To return an empty space that causes the building widget to fill\n' + 'available room, return "Container()". To return an empty space\n' + 'that takes as little room as possible, return "Container(width:\n' + '0.0, height: 0.0)".\n', + ) + ); + expect( + error.toStringDeep(), + equalsIgnoringHashCodes( + 'FlutterError\n' + ' A build function returned null.\n' + ' The offending widget is:\n' + ' Container\n' + ' Build functions must never return null.\n' + ' To return an empty space that causes the building widget to fill\n' + ' available room, return "Container()". To return an empty space\n' + ' that takes as little room as possible, return "Container(width:\n' + ' 0.0, height: 0.0)".\n' + ), + ); + error = null; + } + try { + debugWidgetBuilderValue(widget, widget); + } on FlutterError catch (e) { + error = e; + } finally { + expect(error, isNotNull); + expect(error.diagnostics.length, 3); + expect(error.diagnostics[1], isInstanceOf>()); + expect(error.diagnostics[1].style, DiagnosticsTreeStyle.errorProperty); + expect( + error.diagnostics[1].toStringDeep(), + equalsIgnoringHashCodes( + 'The offending widget is:\n' + ' Container\n' + ) + ); + expect( + error.toStringDeep(), + equalsIgnoringHashCodes( + 'FlutterError\n' + ' A build function returned context.widget.\n' + ' The offending widget is:\n' + ' Container\n' + ' Build functions must never return their BuildContext parameter\'s\n' + ' widget or a child that contains "context.widget". Doing so\n' + ' introduces a loop in the widget tree that can cause the app to\n' + ' crash.\n' + ), + ); + } + }); + + test('debugAssertAllWidgetVarsUnset', () { + debugHighlightDeprecatedWidgets = true; + FlutterError error; + try { + debugAssertAllWidgetVarsUnset('The value of a widget debug variable was changed by the test.'); + } on FlutterError catch (e) { + error = e; + } finally { + expect(error, isNotNull); + expect(error.diagnostics.length, 1); + expect( + error.toStringDeep(), + 'FlutterError\n' + ' The value of a widget debug variable was changed by the test.\n', + ); + } + }); +} diff --git a/packages/flutter/test/widgets/dismissible_test.dart b/packages/flutter/test/widgets/dismissible_test.dart index 65265d51de..3449af9c5c 100644 --- a/packages/flutter/test/widgets/dismissible_test.dart +++ b/packages/flutter/test/widgets/dismissible_test.dart @@ -2,10 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +import 'package:flutter/gestures.dart' show DragStartBehavior; import 'package:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; -import 'package:flutter/gestures.dart' show DragStartBehavior; const double itemExtent = 100.0; Axis scrollDirection = Axis.vertical; @@ -732,4 +732,68 @@ void main() { expect(dismissedItems, isEmpty); expect(confirmDismissDirection, DismissDirection.endToStart); }); + + testWidgets('setState that does not remove the Dismissible from tree should throws Error', (WidgetTester tester) async { + scrollDirection = Axis.vertical; + dismissDirection = DismissDirection.horizontal; + + await tester.pumpWidget(Directionality( + textDirection: TextDirection.ltr, + child: StatefulBuilder( + builder: (BuildContext context, StateSetter setState) { + return ListView( + dragStartBehavior: DragStartBehavior.down, + scrollDirection: scrollDirection, + itemExtent: itemExtent, + children: [ + Dismissible( + dragStartBehavior: DragStartBehavior.down, + key: const ValueKey(1), + direction: dismissDirection, + onDismissed: (DismissDirection direction) { + setState(() { + reportedDismissDirection = direction; + expect(dismissedItems.contains(1), isFalse); + dismissedItems.add(1); + }); + }, + background: background, + dismissThresholds: const {}, + crossAxisEndOffset: crossAxisEndOffset, + child: Container( + width: itemExtent, + height: itemExtent, + child: Text(1.toString()), + ), + ), + ] + ); + }, + ), + )); + expect(dismissedItems, isEmpty); + await dismissItem(tester, 1, gestureDirection: AxisDirection.right); + expect(dismissedItems, equals([1])); + final dynamic exception = tester.takeException(); + expect(exception, isNotNull); + expect(exception, isFlutterError); + final FlutterError error = exception; + expect(error.diagnostics.last.level, DiagnosticLevel.hint); + expect( + error.diagnostics.last.toStringDeep(), + equalsIgnoringHashCodes( + 'Make sure to implement the onDismissed handler and to immediately\n' + 'remove the Dismissible widget from the application once that\n' + 'handler has fired.\n', + ), + ); + expect( + error.toStringDeep(), + 'FlutterError\n' + ' A dismissed Dismissible widget is still part of the tree.\n' + ' Make sure to implement the onDismissed handler and to immediately\n' + ' remove the Dismissible widget from the application once that\n' + ' handler has fired.\n', + ); + }); } diff --git a/packages/flutter/test/widgets/flow_test.dart b/packages/flutter/test/widgets/flow_test.dart index 300975d0cb..73aa3ce178 100644 --- a/packages/flutter/test/widgets/flow_test.dart +++ b/packages/flutter/test/widgets/flow_test.dart @@ -2,9 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import 'package:flutter_test/flutter_test.dart'; -import 'package:flutter/widgets.dart'; import 'package:flutter/rendering.dart'; +import 'package:flutter/widgets.dart'; +import 'package:flutter_test/flutter_test.dart'; class TestFlowDelegate extends FlowDelegate { TestFlowDelegate({this.startOffset}) : super(repaint: startOffset); @@ -45,6 +45,21 @@ class OpacityFlowDelegate extends FlowDelegate { bool shouldRepaint(OpacityFlowDelegate oldDelegate) => opacity != oldDelegate.opacity; } +// OpacityFlowDelegate that paints one of its children twice +class DuplicatePainterOpacityFlowDelegate extends OpacityFlowDelegate { + DuplicatePainterOpacityFlowDelegate(double opacity) : super(opacity); + + @override + void paintChildren(FlowPaintingContext context) { + for (int i = 0; i < context.childCount; ++i) { + context.paintChild(i, opacity: opacity); + } + if (context.childCount > 0) { + context.paintChild(0, opacity: opacity); + } + } +} + void main() { testWidgets('Flow control test', (WidgetTester tester) async { final AnimationController startOffset = AnimationController.unbounded( @@ -100,6 +115,28 @@ void main() { expect(log, equals([0])); }); + testWidgets('paintChild gets called twice', (WidgetTester tester) async { + await tester.pumpWidget( + Flow( + delegate: DuplicatePainterOpacityFlowDelegate(1.0), + children: [ + Container(width: 100.0, height: 100.0), + Container(width: 100.0, height: 100.0), + ], + ), + ); + final dynamic exception = tester.takeException(); + expect(exception, isFlutterError); + final FlutterError error = exception; + expect(error.toStringDeep(), equalsIgnoringHashCodes( + 'FlutterError\n' + ' Cannot call paintChild twice for the same child.\n' + ' The flow delegate of type DuplicatePainterOpacityFlowDelegate\n' + ' attempted to paint child 0 multiple times, which is not\n' + ' permitted.\n' + )); + }); + testWidgets('Flow opacity layer', (WidgetTester tester) async { const double opacity = 0.2; await tester.pumpWidget( diff --git a/packages/flutter/test/widgets/framework_test.dart b/packages/flutter/test/widgets/framework_test.dart index 2b6a6d4e63..5e91dc3588 100644 --- a/packages/flutter/test/widgets/framework_test.dart +++ b/packages/flutter/test/widgets/framework_test.dart @@ -657,6 +657,59 @@ void main() { ); test.includeChild = false; }); + + testWidgets('scheduleBuild while debugBuildingDirtyElements is true', (WidgetTester tester) async { + /// ignore here is required for testing purpose because changing the flag properly is hard + // ignore: invalid_use_of_protected_member + tester.binding.debugBuildingDirtyElements = true; + FlutterError error; + try { + tester.binding.buildOwner.scheduleBuildFor( + DirtyElementWithCustomBuildOwner(tester.binding.buildOwner, Container())); + } on FlutterError catch (e) { + error = e; + } finally { + expect(error, isNotNull); + expect(error.diagnostics.length, 3); + expect(error.diagnostics.last.level, DiagnosticLevel.hint); + expect( + error.diagnostics.last.toStringDeep(), + equalsIgnoringHashCodes( + 'This might be because setState() was called from a layout or\n' + 'paint callback. If a change is needed to the widget tree, it\n' + 'should be applied as the tree is being built. Scheduling a change\n' + 'for the subsequent frame instead results in an interface that\n' + 'lags behind by one frame. If this was done to make your build\n' + 'dependent on a size measured at layout time, consider using a\n' + 'LayoutBuilder, CustomSingleChildLayout, or\n' + 'CustomMultiChildLayout. If, on the other hand, the one frame\n' + 'delay is the desired effect, for example because this is an\n' + 'animation, consider scheduling the frame in a post-frame callback\n' + 'using SchedulerBinding.addPostFrameCallback or using an\n' + 'AnimationController to trigger the animation.\n', + ), + ); + expect( + error.toStringDeep(), + 'FlutterError\n' + ' Build scheduled during frame.\n' + ' While the widget tree was being built, laid out, and painted, a\n' + ' new frame was scheduled to rebuild the widget tree.\n' + ' This might be because setState() was called from a layout or\n' + ' paint callback. If a change is needed to the widget tree, it\n' + ' should be applied as the tree is being built. Scheduling a change\n' + ' for the subsequent frame instead results in an interface that\n' + ' lags behind by one frame. If this was done to make your build\n' + ' dependent on a size measured at layout time, consider using a\n' + ' LayoutBuilder, CustomSingleChildLayout, or\n' + ' CustomMultiChildLayout. If, on the other hand, the one frame\n' + ' delay is the desired effect, for example because this is an\n' + ' animation, consider scheduling the frame in a post-frame callback\n' + ' using SchedulerBinding.addPostFrameCallback or using an\n' + ' AnimationController to trigger the animation.\n', + ); + } + }); } class NullChildTest extends Widget { @@ -681,3 +734,23 @@ class NullChildElement extends Element { @override void performRebuild() { } } + + +class DirtyElementWithCustomBuildOwner extends Element { + DirtyElementWithCustomBuildOwner(BuildOwner buildOwner, Widget widget) + : _owner = buildOwner, super(widget); + + final BuildOwner _owner; + + @override + void forgetChild(Element child) {} + + @override + void performRebuild() {} + + @override + BuildOwner get owner => _owner; + + @override + bool get dirty => true; +} diff --git a/packages/flutter/test/widgets/gesture_detector_test.dart b/packages/flutter/test/widgets/gesture_detector_test.dart index aee62a5872..1d1c170450 100644 --- a/packages/flutter/test/widgets/gesture_detector_test.dart +++ b/packages/flutter/test/widgets/gesture_detector_test.dart @@ -601,6 +601,104 @@ void main() { 'excludeFromSemantics: true', ]); }); + + group('error control test', () { + test('constructor redundant pan and scale', () { + FlutterError error; + try { + GestureDetector(onScaleStart: (_) {}, onPanStart: (_) {},); + } on FlutterError catch (e) { + error = e; + } finally { + expect(error, isNotNull); + expect( + error.toStringDeep(), + 'FlutterError\n' + ' Incorrect GestureDetector arguments.\n' + ' Having both a pan gesture recognizer and a scale gesture\n' + ' recognizer is redundant; scale is a superset of pan.\n' + ' Just use the scale gesture recognizer.\n', + ); + expect(error.diagnostics.last.level, DiagnosticLevel.hint); + expect( + error.diagnostics.last.toStringDeep(), + equalsIgnoringHashCodes( + 'Just use the scale gesture recognizer.\n', + ) + ); + } + }); + + test('constructur duplicate drag recognizer', () { + FlutterError error; + try { + GestureDetector( + onVerticalDragStart: (_) {}, + onHorizontalDragStart: (_) {}, + onPanStart: (_) {}, + ); + } on FlutterError catch (e) { + error = e; + } finally { + expect(error, isNotNull); + expect( + error.toStringDeep(), + 'FlutterError\n' + ' Incorrect GestureDetector arguments.\n' + ' Simultaneously having a vertical drag gesture recognizer, a\n' + ' horizontal drag gesture recognizer, and a pan gesture recognizer\n' + ' will result in the pan gesture recognizer being ignored, since\n' + ' the other two will catch all drags.\n', + ); + } + }); + + testWidgets('replaceGestureRecognizers not during layout', (WidgetTester tester) async { + final GlobalKey key = GlobalKey(); + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: RawGestureDetector( + key: key, + child: Container( + child: const Text('Text'), + ), + ), + ), + ); + FlutterError error; + try { + key.currentState.replaceGestureRecognizers( + {}); + } on FlutterError catch (e) { + error = e; + } finally { + expect(error, isNotNull); + expect(error.diagnostics.last.level, DiagnosticLevel.hint); + expect( + error.diagnostics.last.toStringDeep(), + equalsIgnoringHashCodes( + 'To set the gesture recognizers at other times, trigger a new\n' + 'build using setState() and provide the new gesture recognizers as\n' + 'constructor arguments to the corresponding RawGestureDetector or\n' + 'GestureDetector object.\n' + ), + ); + expect( + error.toStringDeep(), + 'FlutterError\n' + ' Unexpected call to replaceGestureRecognizers() method of\n' + ' RawGestureDetectorState.\n' + ' The replaceGestureRecognizers() method can only be called during\n' + ' the layout phase.\n' + ' To set the gesture recognizers at other times, trigger a new\n' + ' build using setState() and provide the new gesture recognizers as\n' + ' constructor arguments to the corresponding RawGestureDetector or\n' + ' GestureDetector object.\n', + ); + } + }); + }); }); } diff --git a/packages/flutter/test/widgets/heroes_test.dart b/packages/flutter/test/widgets/heroes_test.dart index 14fb9fe078..8fa4ae56f4 100644 --- a/packages/flutter/test/widgets/heroes_test.dart +++ b/packages/flutter/test/widgets/heroes_test.dart @@ -4,6 +4,7 @@ import 'dart:ui' as ui; +import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:flutter/cupertino.dart'; @@ -546,7 +547,31 @@ Future main() async { await tester.tap(find.text('push')); await tester.pump(); - expect(tester.takeException(), isFlutterError); + final dynamic exception = tester.takeException(); + expect(exception, isFlutterError); + final FlutterError error = exception; + expect(error.diagnostics.length, 3); + final DiagnosticsNode last = error.diagnostics.last; + expect(last, isInstanceOf>()); + expect( + last.toStringDeep(), + equalsIgnoringHashCodes( + '# Here is the subtree for one of the offending heroes: Hero\n', + ), + ); + expect(last.style, DiagnosticsTreeStyle.dense); + expect( + error.toStringDeep(), + equalsIgnoringHashCodes( + 'FlutterError\n' + ' There are multiple heroes that share the same tag within a\n' + ' subtree.\n' + ' Within each subtree for which heroes are to be animated (i.e. a\n' + ' PageRoute subtree), each Hero must have a unique non-null tag.\n' + ' In this case, multiple heroes had the following tag: a\n' + ' ├# Here is the subtree for one of the offending heroes: Hero\n', + ), + ); }); testWidgets('Hero push transition interrupted by a pop', (WidgetTester tester) async { diff --git a/packages/flutter/test/widgets/list_body_test.dart b/packages/flutter/test/widgets/list_body_test.dart index e60fc1a08f..90447d6f37 100644 --- a/packages/flutter/test/widgets/list_body_test.dart +++ b/packages/flutter/test/widgets/list_body_test.dart @@ -2,6 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +import 'package:flutter/src/foundation/assertions.dart'; +import 'package:flutter/src/painting/basic_types.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:flutter/widgets.dart'; @@ -106,4 +108,90 @@ void main() { ], ); }); + + testWidgets('Limited space along main axis error', (WidgetTester tester) async { + final FlutterExceptionHandler oldHandler = FlutterError.onError; + final List errors = []; + FlutterError.onError = (FlutterErrorDetails error) => errors.add(error); + try { + await tester.pumpWidget( + SizedBox( + width: 100, + height: 100, + child: Directionality( + textDirection: TextDirection.rtl, + child: ListBody( + mainAxis: Axis.horizontal, + children: children, + ), + ), + ), + ); + } finally { + FlutterError.onError = oldHandler; + } + expect(errors, isNotEmpty); + expect(errors.first.exception, isFlutterError); + expect(errors.first.exception.toStringDeep(), equalsIgnoringHashCodes( + 'FlutterError\n' + ' RenderListBody must have unlimited space along its main axis.\n' + ' RenderListBody does not clip or resize its children, so it must\n' + ' be placed in a parent that does not constrain the main axis.\n' + ' You probably want to put the RenderListBody inside a\n' + ' RenderViewport with a matching main axis.\n' + )); + }); + + testWidgets('Nested ListBody unbounded cross axis error', (WidgetTester tester) async { + final FlutterExceptionHandler oldHandler = FlutterError.onError; + final List errors = []; + FlutterError.onError = (FlutterErrorDetails error) => errors.add(error); + try { + await tester.pumpWidget( + Flex( + textDirection: TextDirection.ltr, + direction: Axis.horizontal, + children: [ + Directionality( + textDirection: TextDirection.ltr, + child: ListBody( + mainAxis: Axis.horizontal, + children: [ + Flex( + textDirection: TextDirection.ltr, + direction: Axis.vertical, + children: [ + Directionality( + textDirection: TextDirection.ltr, + child: ListBody( + mainAxis: Axis.vertical, + children: children, + ), + ), + ], + ), + ], + ), + ), + ], + ), + ); + } finally { + FlutterError.onError = oldHandler; + } + expect(errors, isNotEmpty); + expect(errors.first.exception, isFlutterError); + expect(errors.first.exception.toStringDeep(), equalsIgnoringHashCodes( + 'FlutterError\n' + ' RenderListBody must have a bounded constraint for its cross axis.\n' + ' RenderListBody forces its children to expand to fit the\n' + ' RenderListBody\'s container, so it must be placed in a parent that\n' + ' constrains the cross axis to a finite dimension.\n' + ' If you are attempting to nest a RenderListBody with one direction\n' + ' inside one of another direction, you will want to wrap the inner\n' + ' one inside a box that fixes the dimension in that direction, for\n' + ' example, a RenderIntrinsicWidth or RenderIntrinsicHeight object.\n' + ' This is relatively expensive, however.\n' + )); + }); } diff --git a/packages/flutter/test/widgets/media_query_test.dart b/packages/flutter/test/widgets/media_query_test.dart index 171de4cd55..b9d0e15d0c 100644 --- a/packages/flutter/test/widgets/media_query_test.dart +++ b/packages/flutter/test/widgets/media_query_test.dart @@ -3,6 +3,7 @@ // found in the LICENSE file. import 'dart:ui' show Brightness; +import 'package:flutter/foundation.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:flutter/widgets.dart'; @@ -19,7 +20,27 @@ void main() { ), ); expect(tested, isTrue); - expect(tester.takeException(), isFlutterError); + final dynamic exception = tester.takeException(); + expect(exception, isNotNull); + expect(exception ,isFlutterError); + final FlutterError error = exception; + expect(error.diagnostics.length, 3); + expect(error.diagnostics.last, isInstanceOf>()); + expect( + error.toStringDeep(), + equalsIgnoringHashCodes( + 'FlutterError\n' + ' MediaQuery.of() called with a context that does not contain a\n' + ' MediaQuery.\n' + ' No MediaQuery ancestor could be found starting from the context\n' + ' that was passed to MediaQuery.of(). This can happen because you\n' + ' do not have a WidgetsApp or MaterialApp widget (those widgets\n' + ' introduce a MediaQuery), or it can happen if the context you use\n' + ' comes from a widget above those widgets.\n' + ' The context used was:\n' + ' Builder\n', + ), + ); }); testWidgets('MediaQuery defaults to null', (WidgetTester tester) async { diff --git a/packages/flutter/test/widgets/navigator_test.dart b/packages/flutter/test/widgets/navigator_test.dart index 7f78a74097..27a63ccfe4 100644 --- a/packages/flutter/test/widgets/navigator_test.dart +++ b/packages/flutter/test/widgets/navigator_test.dart @@ -1033,4 +1033,60 @@ void main() { expect(find.byKey(keyA), findsNothing); expect(find.byKey(keyAB), findsNothing); }); + + group('error control test', () { + testWidgets('onUnknownRoute null and onGenerateRoute returns null', (WidgetTester tester) async { + final GlobalKey navigatorKey = GlobalKey(); + await tester.pumpWidget(Navigator( + key: navigatorKey, + onGenerateRoute: (_) => null, + )); + final dynamic exception = tester.takeException(); + expect(exception, isNotNull); + expect(exception, isFlutterError); + final FlutterError error = exception; + expect(error, isNotNull); + expect(error.diagnostics.last, isInstanceOf>()); + expect( + error.toStringDeep(), + equalsIgnoringHashCodes( + 'FlutterError\n' + ' If a Navigator has no onUnknownRoute, then its onGenerateRoute\n' + ' must never return null.\n' + ' When trying to build the route "/", onGenerateRoute returned\n' + ' null, but there was no onUnknownRoute callback specified.\n' + ' The Navigator was:\n' + ' NavigatorState#4d6bf(lifecycle state: created)\n', + ), + ); + }); + + testWidgets('onUnknownRoute null and onGenerateRoute returns null', (WidgetTester tester) async { + final GlobalKey navigatorKey = GlobalKey(); + await tester.pumpWidget(Navigator( + key: navigatorKey, + onGenerateRoute: (_) => null, + onUnknownRoute: (_) => null, + )); + final dynamic exception = tester.takeException(); + expect(exception, isNotNull); + expect(exception, isFlutterError); + final FlutterError error = exception; + expect(error, isNotNull); + expect(error.diagnostics.last, isInstanceOf>()); + expect( + error.toStringDeep(), + equalsIgnoringHashCodes( + 'FlutterError\n' + ' A Navigator\'s onUnknownRoute returned null.\n' + ' When trying to build the route "/", both onGenerateRoute and\n' + ' onUnknownRoute returned null. The onUnknownRoute callback should\n' + ' never return null.\n' + ' The Navigator was:\n' + ' NavigatorState#38036(lifecycle state: created)\n', + ), + ); + }); + }); + } diff --git a/packages/flutter/test/widgets/overlay_test.dart b/packages/flutter/test/widgets/overlay_test.dart index 1ecb6ed60d..eed52a2ab3 100644 --- a/packages/flutter/test/widgets/overlay_test.dart +++ b/packages/flutter/test/widgets/overlay_test.dart @@ -2,6 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +import 'package:flutter/foundation.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:flutter/widgets.dart'; @@ -612,4 +613,48 @@ void main() { expect(buildOrder, [3, 4, 1, 2, 0]); }); + + testWidgets('OverlayState.of() called without Overlay being exist', (WidgetTester tester) async { + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Builder( + builder: (BuildContext context) { + FlutterError error; + final Widget debugRequiredFor = Container(); + try { + Overlay.of(context, debugRequiredFor: debugRequiredFor); + } on FlutterError catch (e) { + error = e; + } finally { + expect(error, isNotNull); + expect(error.diagnostics.length, 5); + expect(error.diagnostics[2].level, DiagnosticLevel.hint); + expect(error.diagnostics[2].toStringDeep(), equalsIgnoringHashCodes( + 'The most common way to add an Overlay to an application is to\n' + 'include a MaterialApp or Navigator widget in the runApp() call.\n', + )); + expect(error.diagnostics[3], isInstanceOf>()); + expect(error.diagnostics[3].value, debugRequiredFor); + expect(error.diagnostics[4], isInstanceOf>()); + expect(error.toStringDeep(), equalsIgnoringHashCodes( + 'FlutterError\n' + ' No Overlay widget found.\n' + ' Container widgets require an Overlay widget ancestor for correct\n' + ' operation.\n' + ' The most common way to add an Overlay to an application is to\n' + ' include a MaterialApp or Navigator widget in the runApp() call.\n' + ' The specific widget that failed to find an overlay was:\n' + ' Container\n' + ' The context from which that widget was searching for an overlay\n' + ' was:\n' + ' Builder\n', + )); + } + return Container(); + } + ), + ), + ); + }); } diff --git a/packages/flutter/test/widgets/scroll_physics_test.dart b/packages/flutter/test/widgets/scroll_physics_test.dart index 665b1376f2..88f8886896 100644 --- a/packages/flutter/test/widgets/scroll_physics_test.dart +++ b/packages/flutter/test/widgets/scroll_physics_test.dart @@ -2,6 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +import 'package:flutter/cupertino.dart'; +import 'package:flutter/foundation.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; @@ -191,4 +193,51 @@ void main() { expect(smallListOverscrollApplied, lessThan(20.0)); }); }); + + test('ClampingScrollPhysics assertion test', () { + const ClampingScrollPhysics physics = ClampingScrollPhysics(); + const double pixels = 500; + final ScrollMetrics position = FixedScrollMetrics( + pixels: pixels, + minScrollExtent: 0, + maxScrollExtent: 1000, + viewportDimension: 0, + axisDirection: AxisDirection.down, + ); + expect(position.pixels, pixels); + FlutterError error; + try { + physics.applyBoundaryConditions(position, pixels); + } on FlutterError catch (e) { + error = e; + } finally { + expect(error, isNotNull); + expect(error.diagnostics.length, 4); + expect(error.diagnostics[2], isInstanceOf>()); + expect(error.diagnostics[2].style, DiagnosticsTreeStyle.errorProperty); + expect(error.diagnostics[2].value, physics); + expect(error.diagnostics[3], isInstanceOf>()); + expect(error.diagnostics[3].style, DiagnosticsTreeStyle.errorProperty); + expect(error.diagnostics[3].value, position); + // RegExp matcher is required here due to flutter web and flutter mobile generating + // slightly different floating point numbers + // in Flutter web 0.0 sometimes just appears as 0. or 0 + expect(error.toStringDeep(), matches(RegExp( + r'''FlutterError + ClampingScrollPhysics\.applyBoundaryConditions\(\) was called + redundantly\. + The proposed new position\, 500(\.\d*)?, is exactly equal to the current + position of the given FixedScrollMetrics, 500(\.\d*)?\. + The applyBoundaryConditions method should only be called when the + value is going to actually change the pixels, otherwise it is + redundant\. + The physics object in question was\: + ClampingScrollPhysics + The position object in question was\: + FixedScrollMetrics\(500(\.\d*)?..\[0(\.\d*)?\]..500(\.\d*)?\) +''', + multiLine: true, + ))); + } + }); } diff --git a/packages/flutter/test/widgets/ticker_provider_test.dart b/packages/flutter/test/widgets/ticker_provider_test.dart index 2cc8eb778a..23f924f76d 100644 --- a/packages/flutter/test/widgets/ticker_provider_test.dart +++ b/packages/flutter/test/widgets/ticker_provider_test.dart @@ -2,6 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +import 'package:flutter/foundation.dart'; +import 'package:flutter/scheduler.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:flutter/material.dart'; @@ -62,6 +64,167 @@ void main() { await tester.pumpWidget(Container()); // the test is that this doesn't crash, like it used to... }); + + group('TickerProviderStateMixin assertion control test', () { + testWidgets('SingleTickerProviderStateMixin create multiple tickers', (WidgetTester tester) async { + final Widget widget = _SingleTickerCreateMultipleTicker(); + await tester.pumpWidget(widget); + final dynamic exception = tester.takeException(); + expect(exception, isNotNull); + expect(exception, isFlutterError); + final FlutterError error = exception; + expect(error.diagnostics.length, 3); + expect(error.diagnostics[2].level, DiagnosticLevel.hint); + expect(error.diagnostics[2].toStringDeep(), equalsIgnoringHashCodes( + 'If a State is used for multiple AnimationController objects, or\n' + 'if it is passed to other objects and those objects might use it\n' + 'more than one time in total, then instead of mixing in a\n' + 'SingleTickerProviderStateMixin, use a regular\n' + 'TickerProviderStateMixin.\n', + )); + expect(error.toStringDeep(), equalsIgnoringHashCodes( + 'FlutterError\n' + ' _SingleTickerCreateMultipleTickerState is a\n' + ' SingleTickerProviderStateMixin but multiple tickers were created.\n' + ' A SingleTickerProviderStateMixin can only be used as a\n' + ' TickerProvider once.\n' + ' If a State is used for multiple AnimationController objects, or\n' + ' if it is passed to other objects and those objects might use it\n' + ' more than one time in total, then instead of mixing in a\n' + ' SingleTickerProviderStateMixin, use a regular\n' + ' TickerProviderStateMixin.\n', + )); + }); + + testWidgets('SingleTickerProviderStateMixin dispose while active', (WidgetTester tester) async { + final GlobalKey<_SingleTickerTestState> key = GlobalKey<_SingleTickerTestState>(); + final Widget widget = Container( + child: _SingleTickerTest(key: key), + ); + await tester.pumpWidget(widget); + FlutterError error; + key.currentState.controller.repeat(); + try { + key.currentState.dispose(); + } on FlutterError catch (e) { + error = e; + } finally { + expect(error, isNotNull); + expect(error.diagnostics.length, 4); + expect(error.diagnostics[2].level, DiagnosticLevel.hint); + expect( + error.diagnostics[2].toStringDeep(), + 'Tickers used by AnimationControllers should be disposed by\n' + 'calling dispose() on the AnimationController itself. Otherwise,\n' + 'the ticker will leak.\n' + ); + expect(error.diagnostics[3], isInstanceOf>()); + expect(error.toStringDeep().split('\n').take(14).join('\n'), equalsIgnoringHashCodes( + 'FlutterError\n' + ' _SingleTickerTestState#00000(ticker active) was disposed with an\n' + ' active Ticker.\n' + ' _SingleTickerTestState created a Ticker via its\n' + ' SingleTickerProviderStateMixin, but at the time dispose() was\n' + ' called on the mixin, that Ticker was still active. The Ticker\n' + ' must be disposed before calling super.dispose().\n' + ' Tickers used by AnimationControllers should be disposed by\n' + ' calling dispose() on the AnimationController itself. Otherwise,\n' + ' the ticker will leak.\n' + ' The offending ticker was:\n' + ' Ticker(created by _SingleTickerTestState#00000(lifecycle state:\n' + ' created))\n' + ' The stack trace when the Ticker was actually created was:' + )); + key.currentState.controller.stop(); + } + }); + + testWidgets('SingleTickerProviderStateMixin dispose while active', (WidgetTester tester) async { + final GlobalKey<_SingleTickerTestState> key = GlobalKey<_SingleTickerTestState>(); + final Widget widget = Container( + child: _SingleTickerTest(key: key), + ); + await tester.pumpWidget(widget); + FlutterError error; + key.currentState.controller.repeat(); + try { + key.currentState.dispose(); + } on FlutterError catch (e) { + error = e; + } finally { + expect(error, isNotNull); + expect(error.diagnostics.length, 4); + expect(error.diagnostics[2].level, DiagnosticLevel.hint); + expect( + error.diagnostics[2].toStringDeep(), + 'Tickers used by AnimationControllers should be disposed by\n' + 'calling dispose() on the AnimationController itself. Otherwise,\n' + 'the ticker will leak.\n' + ); + expect(error.diagnostics[3], isInstanceOf>()); + expect(error.toStringDeep().split('\n').take(14).join('\n'), equalsIgnoringHashCodes( + 'FlutterError\n' + ' _SingleTickerTestState#00000(ticker active) was disposed with an\n' + ' active Ticker.\n' + ' _SingleTickerTestState created a Ticker via its\n' + ' SingleTickerProviderStateMixin, but at the time dispose() was\n' + ' called on the mixin, that Ticker was still active. The Ticker\n' + ' must be disposed before calling super.dispose().\n' + ' Tickers used by AnimationControllers should be disposed by\n' + ' calling dispose() on the AnimationController itself. Otherwise,\n' + ' the ticker will leak.\n' + ' The offending ticker was:\n' + ' Ticker(created by _SingleTickerTestState#00000(lifecycle state:\n' + ' created))\n' + ' The stack trace when the Ticker was actually created was:' + )); + key.currentState.controller.stop(); + } + }); + + testWidgets('ProviderStateMixin dispose while any ticker is active', (WidgetTester tester) async { + final GlobalKey<_MultipleTickerTestState> key = GlobalKey<_MultipleTickerTestState>(); + final Widget widget = Container( + child: _MultipleTickerTest(key: key), + ); + await tester.pumpWidget(widget); + FlutterError error; + key.currentState.controllers.first.repeat(); + try { + key.currentState.dispose(); + } on FlutterError catch (e) { + error = e; + } finally { + expect(error, isNotNull); + expect(error.diagnostics.length, 4); + expect(error.diagnostics[2].level, DiagnosticLevel.hint); + expect( + error.diagnostics[2].toStringDeep(), + 'Tickers used by AnimationControllers should be disposed by\n' + 'calling dispose() on the AnimationController itself. Otherwise,\n' + 'the ticker will leak.\n' + ); + expect(error.diagnostics[3], isInstanceOf>()); + expect(error.toStringDeep().split('\n').take(14).join('\n'), equalsIgnoringHashCodes( + 'FlutterError\n' + ' _MultipleTickerTestState#00000(tickers: tracking 2 tickers) was\n' + ' disposed with an active Ticker.\n' + ' _MultipleTickerTestState created a Ticker via its\n' + ' TickerProviderStateMixin, but at the time dispose() was called on\n' + ' the mixin, that Ticker was still active. All Tickers must be\n' + ' disposed before calling super.dispose().\n' + ' Tickers used by AnimationControllers should be disposed by\n' + ' calling dispose() on the AnimationController itself. Otherwise,\n' + ' the ticker will leak.\n' + ' The offending ticker was:\n' + ' _WidgetTicker(created by\n' + ' _MultipleTickerTestState#00000(lifecycle state: created,\n' + ' tickers: tracking 0 tickers))' + )); + key.currentState.controllers.first.stop(); + } + }); + }); } class BoringTickerTest extends StatefulWidget { @@ -73,3 +236,78 @@ class _BoringTickerTestState extends State with SingleTickerPr @override Widget build(BuildContext context) => Container(); } + +class _SingleTickerTest extends StatefulWidget { + const _SingleTickerTest({Key key}) : super(key: key); + + @override + _SingleTickerTestState createState() => _SingleTickerTestState(); +} + +class _SingleTickerTestState extends State<_SingleTickerTest> with SingleTickerProviderStateMixin { + AnimationController controller; + + @override + void initState() { + super.initState(); + controller = AnimationController( + vsync: this, + duration: const Duration(seconds: 100), + ); + } + + @override + Widget build(BuildContext context) { + return Container(); + } +} + +class _MultipleTickerTest extends StatefulWidget { + const _MultipleTickerTest({Key key}) : super(key: key); + + @override + _MultipleTickerTestState createState() => _MultipleTickerTestState(); +} + +class _MultipleTickerTestState extends State<_MultipleTickerTest> with TickerProviderStateMixin { + List controllers = []; + + @override + void initState() { + super.initState(); + const Duration duration = Duration(seconds: 100); + controllers.add(AnimationController(vsync: this, duration: duration)); + controllers.add(AnimationController(vsync: this, duration: duration)); + } + + @override + Widget build(BuildContext context) { + return Container(); + } +} + +class _SingleTickerCreateMultipleTicker extends StatefulWidget { + @override + _SingleTickerCreateMultipleTickerState createState() => _SingleTickerCreateMultipleTickerState(); +} + +class _SingleTickerCreateMultipleTickerState extends State<_SingleTickerCreateMultipleTicker> with SingleTickerProviderStateMixin { + @override + void initState() { + super.initState(); + AnimationController( + duration: const Duration(seconds: 5), + vsync: this, + ); + AnimationController( + duration: const Duration(seconds: 6), + vsync: this, + ); + } + + @override + Widget build(BuildContext context) { + return Container(); + } +} + diff --git a/packages/flutter_test/lib/src/widget_tester.dart b/packages/flutter_test/lib/src/widget_tester.dart index ba4439f76d..0a8114991d 100644 --- a/packages/flutter_test/lib/src/widget_tester.dart +++ b/packages/flutter_test/lib/src/widget_tester.dart @@ -636,13 +636,16 @@ class WidgetTester extends WidgetController implements HitTestDispatcher, Ticker if (_tickers != null) { for (Ticker ticker in _tickers) { if (ticker.isActive) { - throw FlutterError( - 'A Ticker was active $when.\n' - 'All Tickers must be disposed. Tickers used by AnimationControllers ' - 'should be disposed by calling dispose() on the AnimationController itself. ' - 'Otherwise, the ticker will leak.\n' - 'The offending ticker was: ${ticker.toString(debugIncludeStack: true)}' - ); + throw FlutterError.fromParts([ + ErrorSummary('A Ticker was active $when.'), + ErrorDescription('All Tickers must be disposed.'), + ErrorHint( + 'Tickers used by AnimationControllers ' + 'should be disposed by calling dispose() on the AnimationController itself. ' + 'Otherwise, the ticker will leak.' + ), + ticker.describeForError('The offending ticker was') + ]); } } } @@ -656,13 +659,20 @@ class WidgetTester extends WidgetController implements HitTestDispatcher, Ticker void _verifySemanticsHandlesWereDisposed() { assert(_lastRecordedSemanticsHandles != null); if (binding.pipelineOwner.debugOutstandingSemanticsHandles > _lastRecordedSemanticsHandles) { - throw FlutterError( - 'A SemanticsHandle was active at the end of the test.\n' - 'All SemanticsHandle instances must be disposed by calling dispose() on ' - 'the SemanticsHandle. If your test uses SemanticsTester, it is ' - 'sufficient to call dispose() on SemanticsTester. Otherwise, the ' - 'existing handle will leak into another test and alter its behavior.' - ); + // TODO(jacobr): The hint for this one causes a change in line breaks but + // I think it is for the best. + throw FlutterError.fromParts([ + ErrorSummary('A SemanticsHandle was active at the end of the test.'), + ErrorDescription( + 'All SemanticsHandle instances must be disposed by calling dispose() on ' + 'the SemanticsHandle.' + ), + ErrorHint( + 'If your test uses SemanticsTester, it is ' + 'sufficient to call dispose() on SemanticsTester. Otherwise, the ' + 'existing handle will leak into another test and alter its behavior.' + ) + ]); } _lastRecordedSemanticsHandles = null; } diff --git a/packages/flutter_test/test/widget_tester_test.dart b/packages/flutter_test/test/widget_tester_test.dart index 305f6c66ca..bcca8949d5 100644 --- a/packages/flutter_test/test/widget_tester_test.dart +++ b/packages/flutter_test/test/widget_tester_test.dart @@ -9,6 +9,7 @@ import 'dart:ui'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; +import 'package:flutter/scheduler.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:test_api/test_api.dart' as test_package; import 'package:test_api/src/frontend/async_matcher.dart' show AsyncMatcher; @@ -662,6 +663,41 @@ void main() { expect(find.text('Item 15', skipOffstage: true), findsOneWidget); }); }); + + testWidgets('verifyTickersWereDisposed control test', (WidgetTester tester) async { + FlutterError error; + final Ticker ticker = tester.createTicker((Duration duration) {}); + ticker.start(); + try { + tester.verifyTickersWereDisposed(''); + } on FlutterError catch (e) { + error = e; + } finally { + expect(error, isNotNull); + expect(error.diagnostics.length, 4); + expect(error.diagnostics[2].level, DiagnosticLevel.hint); + expect( + error.diagnostics[2].toStringDeep(), + 'Tickers used by AnimationControllers should be disposed by\n' + 'calling dispose() on the AnimationController itself. Otherwise,\n' + 'the ticker will leak.\n', + ); + expect(error.diagnostics.last, isInstanceOf>()); + expect(error.diagnostics.last.value, ticker); + expect(error.toStringDeep(), startsWith( + 'FlutterError\n' + ' A Ticker was active .\n' + ' All Tickers must be disposed.\n' + ' Tickers used by AnimationControllers should be disposed by\n' + ' calling dispose() on the AnimationController itself. Otherwise,\n' + ' the ticker will leak.\n' + ' The offending ticker was:\n' + ' _TestTicker()\n', + )); + } + ticker.stop(); + }); + } class FakeMatcher extends AsyncMatcher { @@ -679,3 +715,28 @@ class FakeMatcher extends AsyncMatcher { @override Description describe(Description description) => description.add('--fake--'); } + +class _SingleTickerTest extends StatefulWidget { + const _SingleTickerTest({Key key}) : super(key: key); + + @override + _SingleTickerTestState createState() => _SingleTickerTestState(); +} + +class _SingleTickerTestState extends State<_SingleTickerTest> with SingleTickerProviderStateMixin { + AnimationController controller; + + @override + void initState() { + super.initState(); + controller = AnimationController( + vsync: this, + duration: const Duration(seconds: 100), + ) ; + } + + @override + Widget build(BuildContext context) { + return Container(); + } +}