From 42f3709a5a1532f84a2fbcf229927666b6b4e284 Mon Sep 17 00:00:00 2001 From: Michael Goderbauer Date: Wed, 21 Oct 2020 10:09:11 -0700 Subject: [PATCH] Sound null safety for framework and flutter_test (#68642) --- dev/bots/test.dart | 13 +- examples/layers/analysis_options.yaml | 13 ++ .../rendering/custom_coordinate_systems.dart | 2 +- .../layers/rendering/src/sector_layout.dart | 137 +++++++++--------- .../lib/src/cupertino/context_menu.dart | 2 +- packages/flutter/lib/src/cupertino/route.dart | 4 +- .../lib/src/cupertino/tab_scaffold.dart | 5 +- .../lib/src/cupertino/text_selection.dart | 4 +- .../lib/src/foundation/collections.dart | 12 +- .../lib/src/material/bottom_sheet.dart | 2 +- packages/flutter/lib/src/material/dialog.dart | 2 +- .../lib/src/material/material_state.dart | 2 +- .../material/pickers/date_picker_dialog.dart | 2 +- .../pickers/date_range_picker_dialog.dart | 2 +- .../flutter/lib/src/material/popup_menu.dart | 6 +- packages/flutter/lib/src/material/search.dart | 4 +- .../flutter/lib/src/material/time_picker.dart | 2 +- .../lib/src/painting/image_provider.dart | 4 +- packages/flutter/lib/src/rendering/table.dart | 4 +- .../flutter/lib/src/services/restoration.dart | 14 +- .../flutter/lib/src/widgets/dismissible.dart | 6 +- packages/flutter/lib/src/widgets/heroes.dart | 2 +- .../lib/src/widgets/localizations.dart | 2 +- .../lib/src/widgets/modal_barrier.dart | 2 +- .../flutter/lib/src/widgets/navigator.dart | 66 ++++----- .../flutter/lib/src/widgets/restoration.dart | 4 +- .../src/widgets/restoration_properties.dart | 8 +- packages/flutter/lib/src/widgets/routes.dart | 12 +- .../flutter/lib/src/widgets/scrollable.dart | 4 +- packages/flutter/lib/src/widgets/table.dart | 6 +- .../foundation/consolidate_response_test.dart | 2 +- .../foundation/diagnostics_json_test.dart | 36 ++--- .../test/foundation/diagnostics_test.dart | 28 ++-- packages/flutter/test/material/app_test.dart | 4 +- .../test/material/date_picker_test.dart | 96 ++++++------ .../test/material/date_range_picker_test.dart | 70 ++++----- .../flutter/test/material/dialog_test.dart | 8 +- .../test/material/popup_menu_test.dart | 4 +- .../flutter/test/material/search_test.dart | 14 +- .../test/material/time_picker_test.dart | 52 +++---- .../flutter/test/material/will_pop_test.dart | 6 +- .../flutter/test/rendering/mock_canvas.dart | 1 - .../test/services/fake_platform_views.dart | 12 +- .../test/services/platform_views_test.dart | 1 - .../test/widgets/custom_paint_test.dart | 6 +- .../test/widgets/dismissible_test.dart | 4 +- packages/flutter/test/widgets/image_test.dart | 2 +- .../flutter/test/widgets/navigator_test.dart | 8 +- .../widgets/restorable_property_test.dart | 6 +- .../test/widgets/restoration_mixin_test.dart | 22 +-- .../restoration_scopes_moving_test.dart | 2 +- .../widgets/root_restoration_scope_test.dart | 2 +- .../flutter/test/widgets/routes_test.dart | 16 +- .../flutter_test/lib/src/_matchers_io.dart | 16 +- packages/flutter_test/lib/src/binding.dart | 13 +- .../test/test_config/config_test_utils.dart | 2 +- 56 files changed, 400 insertions(+), 381 deletions(-) create mode 100644 examples/layers/analysis_options.yaml diff --git a/dev/bots/test.dart b/dev/bots/test.dart index 9b6bb83a39..b21dec191b 100644 --- a/dev/bots/test.dart +++ b/dev/bots/test.dart @@ -528,7 +528,8 @@ Future _runAddToAppLifeCycleTests() async { Future _runFrameworkTests() async { final bq.BigqueryApi bigqueryApi = await _getBigqueryApi(); - final List nullSafetyOptions = ['--null-assertions', '--no-sound-null-safety']; + final List soundNullSafetyOptions = ['--enable-experiment=non-nullable', '--null-assertions', '--sound-null-safety']; + final List mixedModeNullSafetyOptions = ['--enable-experiment=non-nullable', '--null-assertions', '--no-sound-null-safety']; final List trackWidgetCreationAlternatives = ['--track-widget-creation', '--no-track-widget-creation']; Future runWidgets() async { @@ -536,7 +537,7 @@ Future _runFrameworkTests() async { for (final String trackWidgetCreationOption in trackWidgetCreationAlternatives) { await _runFlutterTest( path.join(flutterRoot, 'packages', 'flutter'), - options: [trackWidgetCreationOption, ...nullSafetyOptions], + options: [trackWidgetCreationOption, ...soundNullSafetyOptions], tableData: bigqueryApi?.tabledata, tests: [ path.join('test', 'widgets') + path.separator ], ); @@ -562,7 +563,7 @@ Future _runFrameworkTests() async { for (final String trackWidgetCreationOption in trackWidgetCreationAlternatives) { await _runFlutterTest( path.join(flutterRoot, 'packages', 'flutter'), - options: [trackWidgetCreationOption, ...nullSafetyOptions], + options: [trackWidgetCreationOption, ...soundNullSafetyOptions], tableData: bigqueryApi?.tabledata, tests: tests, ); @@ -613,14 +614,14 @@ Future _runFrameworkTests() async { await _runFlutterTest(path.join(flutterRoot, 'dev', 'manual_tests'), tableData: bigqueryApi?.tabledata); await _runFlutterTest(path.join(flutterRoot, 'dev', 'tools', 'vitool'), tableData: bigqueryApi?.tabledata); await _runFlutterTest(path.join(flutterRoot, 'examples', 'hello_world'), tableData: bigqueryApi?.tabledata); - await _runFlutterTest(path.join(flutterRoot, 'examples', 'layers'), tableData: bigqueryApi?.tabledata); + await _runFlutterTest(path.join(flutterRoot, 'examples', 'layers'), tableData: bigqueryApi?.tabledata, options: mixedModeNullSafetyOptions); await _runFlutterTest(path.join(flutterRoot, 'dev', 'benchmarks', 'test_apps', 'stocks'), tableData: bigqueryApi?.tabledata); await _runFlutterTest(path.join(flutterRoot, 'packages', 'flutter_driver'), tableData: bigqueryApi?.tabledata, tests: [path.join('test', 'src', 'real_tests')]); await _runFlutterTest(path.join(flutterRoot, 'packages', 'flutter_goldens'), tableData: bigqueryApi?.tabledata); await _runFlutterTest(path.join(flutterRoot, 'packages', 'flutter_localizations'), tableData: bigqueryApi?.tabledata); - await _runFlutterTest(path.join(flutterRoot, 'packages', 'flutter_test'), tableData: bigqueryApi?.tabledata, options: nullSafetyOptions); + await _runFlutterTest(path.join(flutterRoot, 'packages', 'flutter_test'), tableData: bigqueryApi?.tabledata, options: soundNullSafetyOptions); await _runFlutterTest(path.join(flutterRoot, 'packages', 'fuchsia_remote_debug_protocol'), tableData: bigqueryApi?.tabledata); - await _runFlutterTest(path.join(flutterRoot, 'dev', 'integration_tests', 'non_nullable'), options: nullSafetyOptions); + await _runFlutterTest(path.join(flutterRoot, 'dev', 'integration_tests', 'non_nullable'), options: mixedModeNullSafetyOptions); await _runFlutterTest( path.join(flutterRoot, 'dev', 'tracing_tests'), options: ['--enable-vmservice'], diff --git a/examples/layers/analysis_options.yaml b/examples/layers/analysis_options.yaml new file mode 100644 index 0000000000..03733cd330 --- /dev/null +++ b/examples/layers/analysis_options.yaml @@ -0,0 +1,13 @@ +# Use the parent analysis options settings and enable null-experiment. + +include: ../../analysis_options.yaml + +analyzer: + enable-experiment: + - non-nullable + errors: + always_require_non_null_named_parameters: false # not needed with nnbd + type_init_formals: false # https://github.com/dart-lang/linter/issues/2192 + unrelated_type_equality_checks: false # https://github.com/dart-lang/linter/issues/2196 + void_checks: false # https://github.com/dart-lang/linter/issues/2185 + unnecessary_null_comparison: false # Turned off until null-safe rollout is complete. diff --git a/examples/layers/rendering/custom_coordinate_systems.dart b/examples/layers/rendering/custom_coordinate_systems.dart index 5307b567f4..0402b779d9 100644 --- a/examples/layers/rendering/custom_coordinate_systems.dart +++ b/examples/layers/rendering/custom_coordinate_systems.dart @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -// @dart = 2.8 +// @dart = 2.10 // This example shows how to build a render tree with a non-cartesian coordinate // system. Most of the guts of this examples are in src/sector_layout.dart. diff --git a/examples/layers/rendering/src/sector_layout.dart b/examples/layers/rendering/src/sector_layout.dart index 6cb2d3c55d..dbef998c1f 100644 --- a/examples/layers/rendering/src/sector_layout.dart +++ b/examples/layers/rendering/src/sector_layout.dart @@ -2,13 +2,12 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -// @dart = 2.8 +// @dart = 2.10 import 'dart:math' as math; import 'package:flutter/rendering.dart'; import 'package:flutter/gestures.dart'; -import 'package:meta/meta.dart'; const double kTwoPi = 2 * math.pi; @@ -33,11 +32,11 @@ class SectorConstraints extends Constraints { final double maxDeltaTheta; double constrainDeltaRadius(double deltaRadius) { - return deltaRadius.clamp(minDeltaRadius, maxDeltaRadius) as double; + return deltaRadius.clamp(minDeltaRadius, maxDeltaRadius); } double constrainDeltaTheta(double deltaTheta) { - return deltaTheta.clamp(minDeltaTheta, maxDeltaTheta) as double; + return deltaTheta.clamp(minDeltaTheta, maxDeltaTheta); } @override @@ -49,7 +48,7 @@ class SectorConstraints extends Constraints { @override bool debugAssertIsValid({ bool isAppliedConstraint = false, - InformationCollector informationCollector, + InformationCollector? informationCollector, }) { assert(isNormalized); return isNormalized; @@ -102,7 +101,7 @@ abstract class RenderSector extends RenderObject { // RenderSectors always use SectorParentData subclasses, as they need to be // able to read their position information for painting and hit testing. @override - SectorParentData get parentData => super.parentData as SectorParentData; + SectorParentData? get parentData => super.parentData as SectorParentData?; SectorDimensions getIntrinsicDimensions(SectorConstraints constraints, double radius) { return SectorDimensions.withConstraints(constraints); @@ -145,27 +144,27 @@ abstract class RenderSector extends RenderObject { @override Rect get semanticBounds => Rect.fromLTWH(-deltaRadius, -deltaRadius, 2.0 * deltaRadius, 2.0 * deltaRadius); - bool hitTest(SectorHitTestResult result, { double radius, double theta }) { - if (radius < parentData.radius || radius >= parentData.radius + deltaRadius || - theta < parentData.theta || theta >= parentData.theta + deltaTheta) + bool hitTest(SectorHitTestResult result, { required double radius, required double theta }) { + if (radius < parentData!.radius || radius >= parentData!.radius + deltaRadius || + theta < parentData!.theta || theta >= parentData!.theta + deltaTheta) return false; hitTestChildren(result, radius: radius, theta: theta); result.add(SectorHitTestEntry(this, radius: radius, theta: theta)); return true; } - void hitTestChildren(SectorHitTestResult result, { double radius, double theta }) { } + void hitTestChildren(SectorHitTestResult result, { required double radius, required double theta }) { } - double deltaRadius; - double deltaTheta; + late double deltaRadius; + late double deltaTheta; } abstract class RenderDecoratedSector extends RenderSector { - RenderDecoratedSector(BoxDecoration decoration) : _decoration = decoration; + RenderDecoratedSector(BoxDecoration? decoration) : _decoration = decoration; - BoxDecoration _decoration; - BoxDecoration get decoration => _decoration; - set decoration(BoxDecoration value) { + BoxDecoration? _decoration; + BoxDecoration? get decoration => _decoration; + set decoration(BoxDecoration? value) { if (value == _decoration) return; _decoration = value; @@ -182,16 +181,16 @@ abstract class RenderDecoratedSector extends RenderSector { if (_decoration == null) return; - if (_decoration.color != null) { + if (_decoration!.color != null) { final Canvas canvas = context.canvas; - final Paint paint = Paint()..color = _decoration.color; + final Paint paint = Paint()..color = _decoration!.color!; final Path path = Path(); - final double outerRadius = parentData.radius + deltaRadius; + final double outerRadius = parentData!.radius + deltaRadius; final Rect outerBounds = Rect.fromLTRB(offset.dx-outerRadius, offset.dy-outerRadius, offset.dx+outerRadius, offset.dy+outerRadius); - path.arcTo(outerBounds, parentData.theta, deltaTheta, true); - final double innerRadius = parentData.radius; + path.arcTo(outerBounds, parentData!.theta, deltaTheta, true); + final double innerRadius = parentData!.radius; final Rect innerBounds = Rect.fromLTRB(offset.dx-innerRadius, offset.dy-innerRadius, offset.dx+innerRadius, offset.dy+innerRadius); - path.arcTo(innerBounds, parentData.theta + deltaTheta, -deltaTheta, false); + path.arcTo(innerBounds, parentData!.theta + deltaTheta, -deltaTheta, false); path.close(); canvas.drawPath(path, paint); } @@ -202,25 +201,25 @@ abstract class RenderDecoratedSector extends RenderSector { class SectorChildListParentData extends SectorParentData with ContainerParentDataMixin { } class RenderSectorWithChildren extends RenderDecoratedSector with ContainerRenderObjectMixin { - RenderSectorWithChildren(BoxDecoration decoration) : super(decoration); + RenderSectorWithChildren(BoxDecoration? decoration) : super(decoration); @override - void hitTestChildren(SectorHitTestResult result, { double radius, double theta }) { - RenderSector child = lastChild; + void hitTestChildren(SectorHitTestResult result, { required double radius, required double theta }) { + RenderSector? child = lastChild; while (child != null) { if (child.hitTest(result, radius: radius, theta: theta)) return; - final SectorChildListParentData childParentData = child.parentData as SectorChildListParentData; + final SectorChildListParentData childParentData = child.parentData! as SectorChildListParentData; child = childParentData.previousSibling; } } @override void visitChildren(RenderObjectVisitor visitor) { - RenderSector child = lastChild; + RenderSector? child = lastChild; while (child != null) { visitor(child); - final SectorChildListParentData childParentData = child.parentData as SectorChildListParentData; + final SectorChildListParentData childParentData = child.parentData! as SectorChildListParentData; child = childParentData.previousSibling; } } @@ -230,7 +229,7 @@ class RenderSectorRing extends RenderSectorWithChildren { // lays out RenderSector children in a ring RenderSectorRing({ - BoxDecoration decoration, + BoxDecoration? decoration, double deltaRadius = double.infinity, double padding = 0.0, }) : _padding = padding, @@ -275,7 +274,7 @@ class RenderSectorRing extends RenderSectorWithChildren { final double paddingTheta = math.atan(padding / (radius + outerDeltaRadius)); double innerTheta = paddingTheta; // increments with each child double remainingDeltaTheta = math.max(0.0, constraints.maxDeltaTheta - (innerTheta + paddingTheta)); - RenderSector child = firstChild; + RenderSector? child = firstChild; while (child != null) { final SectorConstraints innerConstraints = SectorConstraints( maxDeltaRadius: innerDeltaRadius, @@ -284,7 +283,7 @@ class RenderSectorRing extends RenderSectorWithChildren { final SectorDimensions childDimensions = child.getIntrinsicDimensions(innerConstraints, childRadius); innerTheta += childDimensions.deltaTheta; remainingDeltaTheta -= childDimensions.deltaTheta; - final SectorChildListParentData childParentData = child.parentData as SectorChildListParentData; + final SectorChildListParentData childParentData = child.parentData! as SectorChildListParentData; child = childParentData.nextSibling; if (child != null) { innerTheta += paddingTheta; @@ -302,23 +301,23 @@ class RenderSectorRing extends RenderSectorWithChildren { deltaRadius = constraints.constrainDeltaRadius(desiredDeltaRadius); assert(deltaRadius < double.infinity); final double innerDeltaRadius = deltaRadius - padding * 2.0; - final double childRadius = parentData.radius + padding; - final double paddingTheta = math.atan(padding / (parentData.radius + deltaRadius)); + final double childRadius = parentData!.radius + padding; + final double paddingTheta = math.atan(padding / (parentData!.radius + deltaRadius)); double innerTheta = paddingTheta; // increments with each child double remainingDeltaTheta = constraints.maxDeltaTheta - (innerTheta + paddingTheta); - RenderSector child = firstChild; + RenderSector? child = firstChild; while (child != null) { final SectorConstraints innerConstraints = SectorConstraints( maxDeltaRadius: innerDeltaRadius, maxDeltaTheta: remainingDeltaTheta, ); assert(child.parentData is SectorParentData); - child.parentData.theta = innerTheta; - child.parentData.radius = childRadius; + child.parentData!.theta = innerTheta; + child.parentData!.radius = childRadius; child.layout(innerConstraints, parentUsesSize: true); innerTheta += child.deltaTheta; remainingDeltaTheta -= child.deltaTheta; - final SectorChildListParentData childParentData = child.parentData as SectorChildListParentData; + final SectorChildListParentData childParentData = child.parentData! as SectorChildListParentData; child = childParentData.nextSibling; if (child != null) { innerTheta += paddingTheta; @@ -334,10 +333,10 @@ class RenderSectorRing extends RenderSectorWithChildren { void paint(PaintingContext context, Offset offset) { // TODO(ianh): avoid code duplication super.paint(context, offset); - RenderSector child = firstChild; + RenderSector? child = firstChild; while (child != null) { context.paintChild(child, offset); - final SectorChildListParentData childParentData = child.parentData as SectorChildListParentData; + final SectorChildListParentData childParentData = child.parentData! as SectorChildListParentData; child = childParentData.nextSibling; } } @@ -348,7 +347,7 @@ class RenderSectorSlice extends RenderSectorWithChildren { // lays out RenderSector children in a stack RenderSectorSlice({ - BoxDecoration decoration, + BoxDecoration? decoration, double deltaTheta = kTwoPi, double padding = 0.0, }) : _padding = padding, _desiredDeltaTheta = deltaTheta, super(decoration); @@ -384,12 +383,12 @@ class RenderSectorSlice extends RenderSectorWithChildren { @override SectorDimensions getIntrinsicDimensions(SectorConstraints constraints, double radius) { assert(parentData is SectorParentData); - final double paddingTheta = math.atan(padding / parentData.radius); + final double paddingTheta = math.atan(padding / parentData!.radius); final double outerDeltaTheta = constraints.constrainDeltaTheta(desiredDeltaTheta); final double innerDeltaTheta = outerDeltaTheta - paddingTheta * 2.0; - double childRadius = parentData.radius + padding; + double childRadius = parentData!.radius + padding; double remainingDeltaRadius = constraints.maxDeltaRadius - (padding * 2.0); - RenderSector child = firstChild; + RenderSector? child = firstChild; while (child != null) { final SectorConstraints innerConstraints = SectorConstraints( maxDeltaRadius: remainingDeltaRadius, @@ -398,13 +397,13 @@ class RenderSectorSlice extends RenderSectorWithChildren { final SectorDimensions childDimensions = child.getIntrinsicDimensions(innerConstraints, childRadius); childRadius += childDimensions.deltaRadius; remainingDeltaRadius -= childDimensions.deltaRadius; - final SectorChildListParentData childParentData = child.parentData as SectorChildListParentData; + final SectorChildListParentData childParentData = child.parentData! as SectorChildListParentData; child = childParentData.nextSibling; childRadius += padding; remainingDeltaRadius -= padding; } return SectorDimensions.withConstraints(constraints, - deltaRadius: childRadius - parentData.radius, + deltaRadius: childRadius - parentData!.radius, deltaTheta: outerDeltaTheta); } @@ -413,28 +412,28 @@ class RenderSectorSlice extends RenderSectorWithChildren { assert(parentData is SectorParentData); deltaTheta = constraints.constrainDeltaTheta(desiredDeltaTheta); assert(deltaTheta <= kTwoPi); - final double paddingTheta = math.atan(padding / parentData.radius); - final double innerTheta = parentData.theta + paddingTheta; + final double paddingTheta = math.atan(padding / parentData!.radius); + final double innerTheta = parentData!.theta + paddingTheta; final double innerDeltaTheta = deltaTheta - paddingTheta * 2.0; - double childRadius = parentData.radius + padding; + double childRadius = parentData!.radius + padding; double remainingDeltaRadius = constraints.maxDeltaRadius - (padding * 2.0); - RenderSector child = firstChild; + RenderSector? child = firstChild; while (child != null) { final SectorConstraints innerConstraints = SectorConstraints( maxDeltaRadius: remainingDeltaRadius, maxDeltaTheta: innerDeltaTheta, ); - child.parentData.theta = innerTheta; - child.parentData.radius = childRadius; + child.parentData!.theta = innerTheta; + child.parentData!.radius = childRadius; child.layout(innerConstraints, parentUsesSize: true); childRadius += child.deltaRadius; remainingDeltaRadius -= child.deltaRadius; - final SectorChildListParentData childParentData = child.parentData as SectorChildListParentData; + final SectorChildListParentData childParentData = child.parentData! as SectorChildListParentData; child = childParentData.nextSibling; childRadius += padding; remainingDeltaRadius -= padding; } - deltaRadius = childRadius - parentData.radius; + deltaRadius = childRadius - parentData!.radius; } // offset must point to the center of our circle @@ -443,11 +442,11 @@ class RenderSectorSlice extends RenderSectorWithChildren { void paint(PaintingContext context, Offset offset) { // TODO(ianh): avoid code duplication super.paint(context, offset); - RenderSector child = firstChild; + RenderSector? child = firstChild; while (child != null) { assert(child.parentData is SectorChildListParentData); context.paintChild(child, offset); - final SectorChildListParentData childParentData = child.parentData as SectorChildListParentData; + final SectorChildListParentData childParentData = child.parentData! as SectorChildListParentData; child = childParentData.nextSibling; } } @@ -456,7 +455,7 @@ class RenderSectorSlice extends RenderSectorWithChildren { class RenderBoxToRenderSectorAdapter extends RenderBox with RenderObjectWithChildMixin { - RenderBoxToRenderSectorAdapter({ double innerRadius = 0.0, RenderSector child }) + RenderBoxToRenderSectorAdapter({ double innerRadius = 0.0, RenderSector? child }) : _innerRadius = innerRadius { this.child = child; } @@ -507,13 +506,13 @@ class RenderBoxToRenderSectorAdapter extends RenderBox with RenderObjectWithChil double height = double.infinity, }) { assert(child is RenderSector); - assert(child.parentData is SectorParentData); + assert(child!.parentData is SectorParentData); assert(width != null); assert(height != null); if (!width.isFinite && !height.isFinite) return Size.zero; final double maxChildDeltaRadius = math.max(0.0, math.min(width, height) / 2.0 - innerRadius); - final SectorDimensions childDimensions = child.getIntrinsicDimensions(SectorConstraints(maxDeltaRadius: maxChildDeltaRadius), innerRadius); + final SectorDimensions childDimensions = child!.getIntrinsicDimensions(SectorConstraints(maxDeltaRadius: maxChildDeltaRadius), innerRadius); final double dimension = (innerRadius + childDimensions.deltaRadius) * 2.0; return Size.square(dimension); } @@ -526,12 +525,12 @@ class RenderBoxToRenderSectorAdapter extends RenderBox with RenderObjectWithChil return; } assert(child is RenderSector); - assert(child.parentData is SectorParentData); + assert(child!.parentData is SectorParentData); final double maxChildDeltaRadius = math.min(constraints.maxWidth, constraints.maxHeight) / 2.0 - innerRadius; - child.parentData.radius = innerRadius; - child.parentData.theta = 0.0; - child.layout(SectorConstraints(maxDeltaRadius: maxChildDeltaRadius), parentUsesSize: true); - final double dimension = (innerRadius + child.deltaRadius) * 2.0; + child!.parentData!.radius = innerRadius; + child!.parentData!.theta = 0.0; + child!.layout(SectorConstraints(maxDeltaRadius: maxChildDeltaRadius), parentUsesSize: true); + final double dimension = (innerRadius + child!.deltaRadius) * 2.0; size = constraints.constrain(Size(dimension, dimension)); } @@ -541,12 +540,12 @@ class RenderBoxToRenderSectorAdapter extends RenderBox with RenderObjectWithChil if (child != null) { final Rect bounds = offset & size; // we move the offset to the center of the circle for the RenderSectors - context.paintChild(child, bounds.center); + context.paintChild(child!, bounds.center); } } @override - bool hitTest(BoxHitTestResult result, { Offset position }) { + bool hitTest(BoxHitTestResult result, { required Offset position }) { if (child == null) return false; double x = position.dx; @@ -559,11 +558,11 @@ class RenderBoxToRenderSectorAdapter extends RenderBox with RenderObjectWithChil final double theta = (math.atan2(x, -y) - math.pi / 2.0) % kTwoPi; if (radius < innerRadius) return false; - if (radius >= innerRadius + child.deltaRadius) + if (radius >= innerRadius + child!.deltaRadius) return false; - if (theta > child.deltaTheta) + if (theta > child!.deltaTheta) return false; - child.hitTest(SectorHitTestResult.wrap(result), radius: radius, theta: theta); + child!.hitTest(SectorHitTestResult.wrap(result), radius: radius, theta: theta); result.add(BoxHitTestEntry(this, position)); return true; } @@ -634,7 +633,7 @@ class SectorHitTestEntry extends HitTestEntry { /// Creates a box hit test entry. /// /// The [radius] and [theta] argument must not be null. - SectorHitTestEntry(RenderSector target, { @required this.radius, @required this.theta }) + SectorHitTestEntry(RenderSector target, { required this.radius, required this.theta }) : assert(radius != null), assert(theta != null), super(target); diff --git a/packages/flutter/lib/src/cupertino/context_menu.dart b/packages/flutter/lib/src/cupertino/context_menu.dart index a74d10496e..eaeb4e52f9 100644 --- a/packages/flutter/lib/src/cupertino/context_menu.dart +++ b/packages/flutter/lib/src/cupertino/context_menu.dart @@ -731,7 +731,7 @@ class _ContextMenuRoute extends PopupRoute { } @override - bool didPop(T result) { + bool didPop(T? result) { _updateTweenRects(); return super.didPop(result); } diff --git a/packages/flutter/lib/src/cupertino/route.dart b/packages/flutter/lib/src/cupertino/route.dart index ace6af939c..d1ddf5d2d0 100644 --- a/packages/flutter/lib/src/cupertino/route.dart +++ b/packages/flutter/lib/src/cupertino/route.dart @@ -1049,7 +1049,7 @@ class _CupertinoModalPopupRoute extends PopupRoute { /// * [CupertinoActionSheet], which is the widget usually returned by the /// `builder` argument to [showCupertinoModalPopup]. /// * -Future showCupertinoModalPopup({ +Future showCupertinoModalPopup({ required BuildContext context, required WidgetBuilder builder, ImageFilter? filter, @@ -1134,7 +1134,7 @@ Widget _buildCupertinoDialogTransitions(BuildContext context, Animation /// * [showDialog], which displays a Material-style dialog. /// * [showGeneralDialog], which allows for customization of the dialog popup. /// * -Future showCupertinoDialog({ +Future showCupertinoDialog({ required BuildContext context, required WidgetBuilder builder, bool useRootNavigator = true, diff --git a/packages/flutter/lib/src/cupertino/tab_scaffold.dart b/packages/flutter/lib/src/cupertino/tab_scaffold.dart index 2c65a092a9..306a6ecb7a 100644 --- a/packages/flutter/lib/src/cupertino/tab_scaffold.dart +++ b/packages/flutter/lib/src/cupertino/tab_scaffold.dart @@ -619,8 +619,9 @@ class RestorableCupertinoTabController extends RestorableChangeNotifier throw UnimplementedError(); -} \ No newline at end of file +} diff --git a/packages/flutter/lib/src/foundation/collections.dart b/packages/flutter/lib/src/foundation/collections.dart index d6f9f8fd47..d62b1564f8 100644 --- a/packages/flutter/lib/src/foundation/collections.dart +++ b/packages/flutter/lib/src/foundation/collections.dart @@ -166,7 +166,7 @@ void mergeSort( final int firstLength = middle - start; final int secondLength = end - middle; // secondLength is always the same as firstLength, or one greater. - final List scratchSpace = List.filled(secondLength, null, growable: false); + final List scratchSpace = List.filled(secondLength, list[start]); _mergeSort(list, compare, middle, end, scratchSpace, 0); final int firstTarget = end - firstLength; _mergeSort(list, compare, start, middle, list, firstTarget); @@ -273,7 +273,7 @@ void _mergeSort( int Function(T, T) compare, int start, int end, - List target, + List target, int targetOffset, ) { final int length = end - start; @@ -316,10 +316,10 @@ void _merge( List firstList, int firstStart, int firstEnd, - List secondList, + List secondList, int secondStart, int secondEnd, - List target, + List target, int targetOffset, ) { // No empty lists reaches here. @@ -328,7 +328,7 @@ void _merge( int cursor1 = firstStart; int cursor2 = secondStart; T firstElement = firstList[cursor1++]; - T secondElement = secondList[cursor2++] as T; + T secondElement = secondList[cursor2++]; while (true) { if (compare(firstElement, secondElement) <= 0) { target[targetOffset++] = firstElement; @@ -340,7 +340,7 @@ void _merge( } else { target[targetOffset++] = secondElement; if (cursor2 != secondEnd) { - secondElement = secondList[cursor2++] as T; + secondElement = secondList[cursor2++]; continue; } // Second list empties first. Flushing first list here. diff --git a/packages/flutter/lib/src/material/bottom_sheet.dart b/packages/flutter/lib/src/material/bottom_sheet.dart index 57dd8a22a2..0087473c25 100644 --- a/packages/flutter/lib/src/material/bottom_sheet.dart +++ b/packages/flutter/lib/src/material/bottom_sheet.dart @@ -644,7 +644,7 @@ class _BottomSheetSuspendedCurve extends ParametricCurve { /// * [DraggableScrollableSheet], which allows you to create a bottom sheet /// that grows and then becomes scrollable once it reaches its maximum size. /// * -Future showModalBottomSheet({ +Future showModalBottomSheet({ required BuildContext context, required WidgetBuilder builder, Color? backgroundColor, diff --git a/packages/flutter/lib/src/material/dialog.dart b/packages/flutter/lib/src/material/dialog.dart index a944f75f98..7b93e5da60 100644 --- a/packages/flutter/lib/src/material/dialog.dart +++ b/packages/flutter/lib/src/material/dialog.dart @@ -955,7 +955,7 @@ Widget _buildMaterialDialogTransitions(BuildContext context, Animation a /// * [showCupertinoDialog], which displays an iOS-style dialog. /// * [showGeneralDialog], which allows for customization of the dialog popup. /// * -Future showDialog({ +Future showDialog({ required BuildContext context, WidgetBuilder? builder, bool barrierDismissible = true, diff --git a/packages/flutter/lib/src/material/material_state.dart b/packages/flutter/lib/src/material/material_state.dart index 9403b7509a..59f7eda8b4 100644 --- a/packages/flutter/lib/src/material/material_state.dart +++ b/packages/flutter/lib/src/material/material_state.dart @@ -120,7 +120,7 @@ typedef MaterialPropertyResolver = T Function(Set states); /// } /// ``` /// {@end-tool} -abstract class MaterialStateColor extends Color implements MaterialStateProperty { +abstract class MaterialStateColor extends Color implements MaterialStateProperty { /// Creates a [MaterialStateColor]. const MaterialStateColor(int defaultValue) : super(defaultValue); diff --git a/packages/flutter/lib/src/material/pickers/date_picker_dialog.dart b/packages/flutter/lib/src/material/pickers/date_picker_dialog.dart index 45fe8b48bf..5c1142717d 100644 --- a/packages/flutter/lib/src/material/pickers/date_picker_dialog.dart +++ b/packages/flutter/lib/src/material/pickers/date_picker_dialog.dart @@ -99,7 +99,7 @@ const double _inputFormLandscapeHeight = 108.0; /// * [CalendarDatePicker], which provides the calendar grid used by the date picker dialog. /// * [InputDatePickerFormField], which provides a text input field for entering dates. /// -Future showDatePicker({ +Future showDatePicker({ required BuildContext context, required DateTime initialDate, required DateTime firstDate, diff --git a/packages/flutter/lib/src/material/pickers/date_range_picker_dialog.dart b/packages/flutter/lib/src/material/pickers/date_range_picker_dialog.dart index 6e5042e604..9b5ce429de 100644 --- a/packages/flutter/lib/src/material/pickers/date_range_picker_dialog.dart +++ b/packages/flutter/lib/src/material/pickers/date_range_picker_dialog.dart @@ -105,7 +105,7 @@ const double _inputFormLandscapeHeight = 108.0; /// select a single date. /// * [DateTimeRange], which is used to describe a date range. /// -Future showDateRangePicker({ +Future showDateRangePicker({ required BuildContext context, DateTimeRange? initialDateRange, required DateTime firstDate, diff --git a/packages/flutter/lib/src/material/popup_menu.dart b/packages/flutter/lib/src/material/popup_menu.dart index 47263dd727..7c4df124ff 100644 --- a/packages/flutter/lib/src/material/popup_menu.dart +++ b/packages/flutter/lib/src/material/popup_menu.dart @@ -829,7 +829,7 @@ class _PopupMenuRoute extends PopupRoute { /// calling this method automatically. /// * [SemanticsConfiguration.namesRoute], for a description of edge triggered /// semantics. -Future showMenu({ +Future showMenu({ required BuildContext context, required RelativeRect position, required List> items, @@ -1088,7 +1088,7 @@ class PopupMenuButtonState extends State> { final List> items = widget.itemBuilder(context); // Only show the menu if there is something to show if (items.isNotEmpty) { - showMenu( + showMenu( context: context, elevation: widget.elevation ?? popupMenuTheme.elevation, items: items, @@ -1098,7 +1098,7 @@ class PopupMenuButtonState extends State> { color: widget.color ?? popupMenuTheme.color, captureInheritedThemes: widget.captureInheritedThemes, ) - .then((T newValue) { + .then((T? newValue) { if (!mounted) return null; if (newValue == null) { diff --git a/packages/flutter/lib/src/material/search.dart b/packages/flutter/lib/src/material/search.dart index 0e4aeb9d76..e4e8996a60 100644 --- a/packages/flutter/lib/src/material/search.dart +++ b/packages/flutter/lib/src/material/search.dart @@ -49,7 +49,7 @@ import 'theme.dart'; /// See also: /// /// * [SearchDelegate] to define the content of the search page. -Future showSearch({ +Future showSearch({ required BuildContext context, required SearchDelegate delegate, String? query = '', @@ -387,7 +387,7 @@ class _SearchPageRoute extends PageRoute { } @override - void didComplete(T result) { + void didComplete(T? result) { super.didComplete(result); assert(delegate._route == this); delegate._route = null; diff --git a/packages/flutter/lib/src/material/time_picker.dart b/packages/flutter/lib/src/material/time_picker.dart index d4e46c108d..1b465e5241 100644 --- a/packages/flutter/lib/src/material/time_picker.dart +++ b/packages/flutter/lib/src/material/time_picker.dart @@ -2175,7 +2175,7 @@ class _TimePickerDialogState extends State<_TimePickerDialog> { /// date picker. /// * [TimePickerThemeData], which allows you to customize the colors, /// typography, and shape of the time picker. -Future showTimePicker({ +Future showTimePicker({ required BuildContext context, required TimeOfDay initialTime, TransitionBuilder? builder, diff --git a/packages/flutter/lib/src/painting/image_provider.dart b/packages/flutter/lib/src/painting/image_provider.dart index 110ca73540..8ccae23844 100644 --- a/packages/flutter/lib/src/painting/image_provider.dart +++ b/packages/flutter/lib/src/painting/image_provider.dart @@ -379,12 +379,12 @@ abstract class ImageProvider { /// [FlutterError.onError], and the method will return null. /// /// A completed return value of null indicates that an error has occurred. - Future obtainCacheStatus({ + Future obtainCacheStatus({ required ImageConfiguration configuration, ImageErrorListener? handleError, }) { assert(configuration != null); - final Completer completer = Completer(); + final Completer completer = Completer(); _createErrorHandlerAndKey( configuration, (T key, ImageErrorListener innerHandleError) { diff --git a/packages/flutter/lib/src/rendering/table.dart b/packages/flutter/lib/src/rendering/table.dart index 476def3a98..35174c4c13 100644 --- a/packages/flutter/lib/src/rendering/table.dart +++ b/packages/flutter/lib/src/rendering/table.dart @@ -390,7 +390,7 @@ class RenderTable extends RenderBox { _textBaseline = textBaseline, _defaultVerticalAlignment = defaultVerticalAlignment, _configuration = configuration { - _children = []..length = _columns * _rows; + _children = []..length = _columns * _rows; this.rowDecorations = rowDecorations; // must use setter to initialize box painters array children?.forEach(addRow); } @@ -645,7 +645,7 @@ class RenderTable extends RenderBox { // update our internal values _columns = columns; _rows = cells.length ~/ columns; - _children = cells.toList(); + _children = List.from(cells); assert(_children.length == rows * columns); markNeedsLayout(); } diff --git a/packages/flutter/lib/src/services/restoration.dart b/packages/flutter/lib/src/services/restoration.dart index 42e33eec12..54d9a94531 100644 --- a/packages/flutter/lib/src/services/restoration.dart +++ b/packages/flutter/lib/src/services/restoration.dart @@ -151,13 +151,13 @@ class RestorationManager extends ChangeNotifier { return SynchronousFuture(_rootBucket); } if (_pendingRootBucket == null) { - _pendingRootBucket = Completer(); + _pendingRootBucket = Completer(); _getRootBucketFromEngine(); } return _pendingRootBucket!.future; } RestorationBucket? _rootBucket; // May be null to indicate that restoration is turned off. - Completer? _pendingRootBucket; + Completer? _pendingRootBucket; bool _rootBucketIsValid = false; /// Returns true for the frame after [rootBucket] has been replaced with a @@ -186,7 +186,7 @@ class RestorationManager extends ChangeNotifier { void _parseAndHandleRestorationUpdateFromEngine(Map? update) { handleRestorationUpdateFromEngine( enabled: update != null && update['enabled'] as bool, - data: update == null ? null : update['data'] as Uint8List, + data: update == null ? null : update['data'] as Uint8List?, ); } @@ -580,10 +580,10 @@ class RestorationBucket { /// * [remove], which removes a value from the bucket. /// * [contains], which checks whether any value is stored under a given /// restoration ID. - P read

(String restorationId) { + P? read

(String restorationId) { assert(_debugAssertNotDisposed()); assert(restorationId != null); - return _rawValues[restorationId] as P; + return _rawValues[restorationId] as P?; } /// Stores the provided `value` of type `P` under the provided `restorationId` @@ -624,11 +624,11 @@ class RestorationBucket { /// * [write], which stores a value in the bucket. /// * [contains], which checks whether any value is stored under a given /// restoration ID. - P remove

(String restorationId) { + P? remove

(String restorationId) { assert(_debugAssertNotDisposed()); assert(restorationId != null); final bool needsUpdate = _rawValues.containsKey(restorationId); - final P result = _rawValues.remove(restorationId) as P; + final P? result = _rawValues.remove(restorationId) as P?; if (_rawValues.isEmpty) { _rawData.remove(_valuesMapKey); } diff --git a/packages/flutter/lib/src/widgets/dismissible.dart b/packages/flutter/lib/src/widgets/dismissible.dart index 799880c228..b6c823f0cf 100644 --- a/packages/flutter/lib/src/widgets/dismissible.dart +++ b/packages/flutter/lib/src/widgets/dismissible.dart @@ -28,7 +28,7 @@ typedef DismissDirectionCallback = void Function(DismissDirection direction); /// confirm or veto a dismiss gesture. /// /// Used by [Dismissible.confirmDismiss]. -typedef ConfirmDismissCallback = Future Function(DismissDirection direction); +typedef ConfirmDismissCallback = Future Function(DismissDirection direction); /// The direction in which a [Dismissible] can be dismissed. enum DismissDirection { @@ -120,7 +120,7 @@ class Dismissible extends StatefulWidget { /// If the returned Future completes true, then this widget will be /// dismissed, otherwise it will be moved back to its original location. /// - /// If the returned Future completes to false or null the [onResize] + /// If the returned Future completes to false or null the [onResize] /// and [onDismissed] callbacks will not run. final ConfirmDismissCallback? confirmDismiss; @@ -458,7 +458,7 @@ class _DismissibleState extends State with TickerProviderStateMixin updateKeepAlive(); } - Future _confirmStartResizeAnimation() async { + Future _confirmStartResizeAnimation() async { if (widget.confirmDismiss != null) { final DismissDirection direction = _dismissDirection!; assert(direction != null); diff --git a/packages/flutter/lib/src/widgets/heroes.dart b/packages/flutter/lib/src/widgets/heroes.dart index f7377cdafb..572beb195e 100644 --- a/packages/flutter/lib/src/widgets/heroes.dart +++ b/packages/flutter/lib/src/widgets/heroes.dart @@ -300,7 +300,7 @@ class Hero extends StatefulWidget { // the Hero is inside a nested Navigator and should only be // considered for animation if it is part of the top-most route in // that nested Navigator and if that route is also a PageRoute. - final ModalRoute? heroRoute = ModalRoute.of(hero); + final ModalRoute? heroRoute = ModalRoute.of(hero); if (heroRoute != null && heroRoute is PageRoute && heroRoute.isCurrent) { inviteHero(hero, tag); } diff --git a/packages/flutter/lib/src/widgets/localizations.dart b/packages/flutter/lib/src/widgets/localizations.dart index ef61693ded..8de4803a9e 100644 --- a/packages/flutter/lib/src/widgets/localizations.dart +++ b/packages/flutter/lib/src/widgets/localizations.dart @@ -450,7 +450,7 @@ class Localizations extends StatefulWidget { assert(context != null); assert(type != null); final _LocalizationsScope? scope = context.dependOnInheritedWidgetOfExactType<_LocalizationsScope>(); - return scope?.localizationsState.resourcesFor(type); + return scope?.localizationsState.resourcesFor(type); } @override diff --git a/packages/flutter/lib/src/widgets/modal_barrier.dart b/packages/flutter/lib/src/widgets/modal_barrier.dart index c4d3ce3c4c..3d1b693785 100644 --- a/packages/flutter/lib/src/widgets/modal_barrier.dart +++ b/packages/flutter/lib/src/widgets/modal_barrier.dart @@ -159,7 +159,7 @@ class AnimatedModalBarrier extends AnimatedWidget { /// /// * [ModalRoute.barrierColor], which controls this property for the /// [AnimatedModalBarrier] built by [ModalRoute] pages. - Animation get color => listenable as Animation; + Animation get color => listenable as Animation; /// Whether touching the barrier will pop the current route off the [Navigator]. /// diff --git a/packages/flutter/lib/src/widgets/navigator.dart b/packages/flutter/lib/src/widgets/navigator.dart index 33ad7a6053..6884e8908b 100644 --- a/packages/flutter/lib/src/widgets/navigator.dart +++ b/packages/flutter/lib/src/widgets/navigator.dart @@ -306,8 +306,8 @@ abstract class Route { /// The future completes with the value given to [Navigator.pop], if any, or /// else the value of [currentResult]. See [didComplete] for more discussion /// on this topic. - Future get popped => _popCompleter.future; - final Completer _popCompleter = Completer(); + Future get popped => _popCompleter.future; + final Completer _popCompleter = Completer(); /// A request was made to pop this route. If the route can handle it /// internally (e.g. because it has its own stack of internal state) then @@ -329,7 +329,7 @@ abstract class Route { /// See [popped], [didComplete], and [currentResult] for a discussion of the /// `result` argument. @mustCallSuper - bool didPop(T result) { + bool didPop(T? result) { didComplete(result); return true; } @@ -351,7 +351,7 @@ abstract class Route { /// iOS-style back gesture. See [NavigatorState.didStartUserGesture]. @protected @mustCallSuper - void didComplete(T result) { + void didComplete(T? result) { _popCompleter.complete(result ?? currentResult); } @@ -1693,7 +1693,7 @@ class Navigator extends StatefulWidget { /// * [restorablePushNamed], which pushes a route that can be restored /// during state restoration. @optionalTypeArgs - static Future pushNamed( + static Future pushNamed( BuildContext context, String routeName, { Object? arguments, @@ -1810,7 +1810,7 @@ class Navigator extends StatefulWidget { /// * [restorablePushReplacementNamed], which pushes a replacement route that /// can be restored during state restoration. @optionalTypeArgs - static Future pushReplacementNamed( + static Future pushReplacementNamed( BuildContext context, String routeName, { TO? result, @@ -1904,7 +1904,7 @@ class Navigator extends StatefulWidget { /// * [restorablePopAndPushNamed], which pushes a new route that can be /// restored during state restoration. @optionalTypeArgs - static Future popAndPushNamed( + static Future popAndPushNamed( BuildContext context, String routeName, { TO? result, @@ -2008,7 +2008,7 @@ class Navigator extends StatefulWidget { /// * [restorablePushNamedAndRemoveUntil], which pushes a new route that can /// be restored during state restoration. @optionalTypeArgs - static Future pushNamedAndRemoveUntil( + static Future pushNamedAndRemoveUntil( BuildContext context, String newRouteName, RoutePredicate predicate, { @@ -2087,7 +2087,7 @@ class Navigator extends StatefulWidget { /// * [restorablePush], which pushes a route that can be restored during /// state restoration. @optionalTypeArgs - static Future push(BuildContext context, Route route) { + static Future push(BuildContext context, Route route) { return Navigator.of(context)!.push(route); } @@ -2190,7 +2190,7 @@ class Navigator extends StatefulWidget { /// * [restorablePushReplacement], which pushes a replacement route that can /// be restored during state restoration. @optionalTypeArgs - static Future pushReplacement(BuildContext context, Route newRoute, { TO? result }) { + static Future pushReplacement(BuildContext context, Route newRoute, { TO? result }) { return Navigator.of(context)!.pushReplacement(newRoute, result: result); } @@ -2295,7 +2295,7 @@ class Navigator extends StatefulWidget { /// * [restorablePushAndRemoveUntil], which pushes a route that can be /// restored during state restoration. @optionalTypeArgs - static Future pushAndRemoveUntil(BuildContext context, Route newRoute, RoutePredicate predicate) { + static Future pushAndRemoveUntil(BuildContext context, Route newRoute, RoutePredicate predicate) { return Navigator.of(context)!.pushAndRemoveUntil(newRoute, predicate); } @@ -2876,7 +2876,7 @@ class _RouteEntry extends RouteTransitionRecord { // User-provided restoration ids of Pages are prefixed with 'p+'. Generated // ids for pageless routes are prefixed with 'r+' to avoid clashes. if (hasPage) { - final Page page = route.settings as Page; + final Page page = route.settings as Page; return page.restorationId != null ? 'p+${page.restorationId}' : null; } if (restorationInformation != null) { @@ -4000,7 +4000,7 @@ class NavigatorState extends State with TickerProviderStateMixin, Res /// * [restorablePushNamed], which pushes a route that can be restored /// during state restoration. @optionalTypeArgs - Future pushNamed( + Future pushNamed( String routeName, { Object? arguments, }) { @@ -4067,7 +4067,7 @@ class NavigatorState extends State with TickerProviderStateMixin, Res /// * [restorablePushReplacementNamed], which pushes a replacement route that /// can be restored during state restoration. @optionalTypeArgs - Future pushReplacementNamed( + Future pushReplacementNamed( String routeName, { TO? result, Object? arguments, @@ -4137,7 +4137,7 @@ class NavigatorState extends State with TickerProviderStateMixin, Res /// * [restorablePopAndPushNamed], which pushes a new route that can be /// restored during state restoration. @optionalTypeArgs - Future popAndPushNamed( + Future popAndPushNamed( String routeName, { TO? result, Object? arguments, @@ -4200,7 +4200,7 @@ class NavigatorState extends State with TickerProviderStateMixin, Res /// * [restorablePushNamedAndRemoveUntil], which pushes a new route that can /// be restored during state restoration. @optionalTypeArgs - Future pushNamedAndRemoveUntil( + Future pushNamedAndRemoveUntil( String newRouteName, RoutePredicate predicate, { Object? arguments, @@ -4266,7 +4266,7 @@ class NavigatorState extends State with TickerProviderStateMixin, Res /// * [restorablePush], which pushes a route that can be restored during /// state restoration. @optionalTypeArgs - Future push(Route route) { + Future push(Route route) { _pushEntry(_RouteEntry(route, initialState: _RouteLifecycle.push)); return route.popped; } @@ -4410,7 +4410,7 @@ class NavigatorState extends State with TickerProviderStateMixin, Res /// * [restorablePushReplacement], which pushes a replacement route that can /// be restored during state restoration. @optionalTypeArgs - Future pushReplacement(Route newRoute, { TO? result }) { + Future pushReplacement(Route newRoute, { TO? result }) { assert(newRoute != null); assert(newRoute._navigator == null); _pushReplacementEntry(_RouteEntry(newRoute, initialState: _RouteLifecycle.pushReplace), result); @@ -4516,7 +4516,7 @@ class NavigatorState extends State with TickerProviderStateMixin, Res /// * [restorablePushAndRemoveUntil], which pushes a route that can be /// restored during state restoration. @optionalTypeArgs - Future pushAndRemoveUntil(Route newRoute, RoutePredicate predicate) { + Future pushAndRemoveUntil(Route newRoute, RoutePredicate predicate) { assert(newRoute != null); assert(newRoute._navigator == null); assert(newRoute.overlayEntries.isEmpty); @@ -5116,9 +5116,9 @@ abstract class _RestorationInformation { factory _RestorationInformation.fromSerializableData(Object data) { assert(data != null); - final List casted = data as List; + final List casted = data as List; assert(casted.isNotEmpty); - final _RouteRestorationType type = _RouteRestorationType.values[casted[0] as int]; + final _RouteRestorationType type = _RouteRestorationType.values[casted[0]! as int]; switch (type) { case _RouteRestorationType.named: return _NamedRestorationInformation.fromSerializableData(casted.sublist(1)); @@ -5167,11 +5167,11 @@ class _NamedRestorationInformation extends _RestorationInformation { required this.restorationScopeId, }) : assert(name != null), super(_RouteRestorationType.named); - factory _NamedRestorationInformation.fromSerializableData(List data) { + factory _NamedRestorationInformation.fromSerializableData(List data) { assert(data.length >= 2); return _NamedRestorationInformation( - restorationScopeId: data[0] as int, - name: data[1] as String, + restorationScopeId: data[0]! as int, + name: data[1]! as String, arguments: data.length > 2 ? data[2] : null, ); } @@ -5206,11 +5206,11 @@ class _AnonymousRestorationInformation extends _RestorationInformation { required this.restorationScopeId, }) : assert(routeBuilder != null), super(_RouteRestorationType.anonymous); - factory _AnonymousRestorationInformation.fromSerializableData(List data) { + factory _AnonymousRestorationInformation.fromSerializableData(List data) { assert(data.length > 1); - final RestorableRouteBuilder routeBuilder = ui.PluginUtilities.getCallbackFromHandle(ui.CallbackHandle.fromRawHandle(data[1] as int))! as RestorableRouteBuilder; + final RestorableRouteBuilder routeBuilder = ui.PluginUtilities.getCallbackFromHandle(ui.CallbackHandle.fromRawHandle(data[1]! as int))! as RestorableRouteBuilder; return _AnonymousRestorationInformation( - restorationScopeId: data[0] as int, + restorationScopeId: data[0]! as int, routeBuilder: routeBuilder, arguments: data.length > 2 ? data[2] : null, ); @@ -5383,10 +5383,10 @@ class _HistoryProperty extends RestorableProperty>?> { } @override - Map>? fromPrimitives(Object data) { - final Map casted = data as Map; - return casted.map>((dynamic key, dynamic value) => MapEntry>( - key as String, + Map>? fromPrimitives(Object? data) { + final Map casted = data! as Map; + return casted.map>((dynamic key, dynamic value) => MapEntry>( + key as String?, List.from(value as List, growable: true), )); } @@ -5694,9 +5694,9 @@ class RestorableRouteFuture extends RestorableProperty { } @override - String fromPrimitives(Object data) { + String fromPrimitives(Object? data) { assert(data != null); - return data as String; + return data! as String; } bool _disposed = false; diff --git a/packages/flutter/lib/src/widgets/restoration.dart b/packages/flutter/lib/src/widgets/restoration.dart index e83c6ed953..9fc259f523 100644 --- a/packages/flutter/lib/src/widgets/restoration.dart +++ b/packages/flutter/lib/src/widgets/restoration.dart @@ -425,7 +425,7 @@ abstract class RestorableProperty extends ChangeNotifier { /// [RestorableProperty]. Whenever new restoration data has been provided to /// the [RestorationMixin] the property is registered to, either this method /// or [createDefaultValue] is called before [initWithValue] is invoked. - T fromPrimitives(Object data); + T fromPrimitives(Object? data); /// Called by the [RestorationMixin] with the `value` returned by either /// [createDefaultValue] or [fromPrimitives] to set the value that this @@ -884,7 +884,7 @@ mixin RestorationMixin on State { /// restore the internal state of a [State] object, it may be removed from the /// restoration data by calling this method. @protected - void unregisterFromRestoration(RestorableProperty property) { + void unregisterFromRestoration(RestorableProperty property) { assert(property != null); assert(property._owner == this); _bucket?.remove(property._restorationId!); diff --git a/packages/flutter/lib/src/widgets/restoration_properties.dart b/packages/flutter/lib/src/widgets/restoration_properties.dart index 430e6cb387..3a7221e661 100644 --- a/packages/flutter/lib/src/widgets/restoration_properties.dart +++ b/packages/flutter/lib/src/widgets/restoration_properties.dart @@ -173,9 +173,9 @@ class _RestorablePrimitiveValue extends RestorableValue { } @override - T fromPrimitives(Object serialized) { + T fromPrimitives(Object? serialized) { assert(serialized != null); - return serialized as T; + return serialized! as T; } @override @@ -360,8 +360,8 @@ class RestorableTextEditingController extends RestorableChangeNotifier extends Route { bool get finishedWhenPopped => true; @override - bool didPop(T result) { + bool didPop(T? result) { final bool returnValue = super.didPop(result); assert(returnValue); if (finishedWhenPopped) @@ -90,8 +90,8 @@ abstract class TransitionRoute extends OverlayRoute { /// This future completes once the animation has been dismissed. That will be /// after [popped], because [popped] typically completes before the animation /// even starts, as soon as the route is popped. - Future get completed => _transitionCompleter.future; - final Completer _transitionCompleter = Completer(); + Future get completed => _transitionCompleter.future; + final Completer _transitionCompleter = Completer(); /// {@template flutter.widgets.transitionRoute.transitionDuration} /// The duration the transition going forwards. @@ -235,7 +235,7 @@ abstract class TransitionRoute extends OverlayRoute { } @override - bool didPop(T result) { + bool didPop(T? result) { assert(_controller != null, '$runtimeType.didPop called before calling install() or after calling dispose().'); assert(!_transitionCompleter.isCompleted, 'Cannot reuse a $runtimeType after disposing it.'); _result = result; @@ -631,7 +631,7 @@ mixin LocalHistoryRoute on Route { } @override - bool didPop(T result) { + bool didPop(T? result) { if (_localHistory != null && _localHistory!.isNotEmpty) { final LocalHistoryEntry entry = _localHistory!.removeLast(); assert(entry._owner == this); @@ -1818,7 +1818,7 @@ class _DialogRoute extends PopupRoute { /// /// * [showDialog], which displays a Material-style dialog. /// * [showCupertinoDialog], which displays an iOS-style dialog. -Future showGeneralDialog({ +Future showGeneralDialog({ required BuildContext context, required RoutePageBuilder pageBuilder, bool barrierDismissible = false, diff --git a/packages/flutter/lib/src/widgets/scrollable.dart b/packages/flutter/lib/src/widgets/scrollable.dart index d6ffbc349e..8b3d819439 100644 --- a/packages/flutter/lib/src/widgets/scrollable.dart +++ b/packages/flutter/lib/src/widgets/scrollable.dart @@ -1084,8 +1084,8 @@ class _RestorableScrollOffset extends RestorableValue { } @override - double fromPrimitives(Object data) { - return data as double; + double fromPrimitives(Object? data) { + return data! as double; } @override diff --git a/packages/flutter/lib/src/widgets/table.dart b/packages/flutter/lib/src/widgets/table.dart index d3e42af481..ec60a50166 100644 --- a/packages/flutter/lib/src/widgets/table.dart +++ b/packages/flutter/lib/src/widgets/table.dart @@ -303,16 +303,16 @@ class _TableElement extends RenderObjectElement { } @override - void insertRenderObjectChild(RenderObject child, IndexedSlot? slot) { + void insertRenderObjectChild(RenderObject child, dynamic slot) { renderObject.setupParentData(child); } @override - void moveRenderObjectChild(RenderObject child, IndexedSlot? oldSlot, IndexedSlot? newSlot) { + void moveRenderObjectChild(RenderObject child, dynamic oldSlot, dynamic newSlot) { } @override - void removeRenderObjectChild(RenderObject child, IndexedSlot? slot) { + void removeRenderObjectChild(RenderObject child, dynamic slot) { final TableCellParentData childParentData = child.parentData! as TableCellParentData; renderObject.setChild(childParentData.x!, childParentData.y!, null); } diff --git a/packages/flutter/test/foundation/consolidate_response_test.dart b/packages/flutter/test/foundation/consolidate_response_test.dart index b4775f9abe..b6288133ab 100644 --- a/packages/flutter/test/foundation/consolidate_response_test.dart +++ b/packages/flutter/test/foundation/consolidate_response_test.dart @@ -111,7 +111,7 @@ void main() { test('Notifies onBytesReceived with gzipped numbers', () async { response.contentLength = gzipped.length; - final List records = []; + final List records = []; await consolidateHttpClientResponseBytes( response, onBytesReceived: (int cumulative, int? total) { diff --git a/packages/flutter/test/foundation/diagnostics_json_test.dart b/packages/flutter/test/foundation/diagnostics_json_test.dart index 77ad289caa..facc1c1181 100644 --- a/packages/flutter/test/foundation/diagnostics_json_test.dart +++ b/packages/flutter/test/foundation/diagnostics_json_test.dart @@ -76,7 +76,7 @@ void main() { test('subtreeDepth 1', () { final Map result = testTree.toDiagnosticsNode().toJsonMap(const DiagnosticsSerializationDelegate(subtreeDepth: 1)); expect(result.containsKey('properties'), isFalse); - final List> children = result['children']! as List>; + final List> children = result['children']! as List>; expect(children[0].containsKey('children'), isFalse); expect(children[1].containsKey('children'), isFalse); expect(children[2].containsKey('children'), isFalse); @@ -85,7 +85,7 @@ void main() { test('subtreeDepth 5', () { final Map result = testTree.toDiagnosticsNode().toJsonMap(const DiagnosticsSerializationDelegate(subtreeDepth: 5)); expect(result.containsKey('properties'), isFalse); - final List> children = result['children']! as List>; + final List> children = result['children']! as List>; expect(children[0]['children'], hasLength(0)); expect(children[1]['children'], hasLength(3)); expect(children[2]['children'], hasLength(0)); @@ -103,7 +103,7 @@ void main() { subtreeDepth: 1, )); expect(result['properties'], hasLength(7)); - final List> children = result['children']! as List>; + final List> children = result['children']! as List>; expect(children, hasLength(3)); expect(children[0]['properties'], hasLength(0)); expect(children[1]['properties'], hasLength(2)); @@ -119,13 +119,13 @@ void main() { }, )); expect(result['foo'], isTrue); - final List> properties = result['properties']! as List>; + final List> properties = result['properties']! as List>; expect(properties, hasLength(7)); - expect(properties.every((Map property) => property['foo'] == true), isTrue); + expect(properties.every((Map property) => property['foo'] == true), isTrue); - final List> children = result['children']! as List>; + final List> children = result['children']! as List>; expect(children, hasLength(3)); - expect(children.every((Map child) => child['foo'] == true), isTrue); + expect(children.every((Map child) => child['foo'] == true), isTrue); }); test('filterProperties - sublist', () { @@ -135,9 +135,9 @@ void main() { return nodes.whereType().toList(); }, )); - final List> properties = result['properties']! as List>; + final List> properties = result['properties']! as List>; expect(properties, hasLength(3)); - expect(properties.every((Map property) => property['type'] == 'StringProperty'), isTrue); + expect(properties.every((Map property) => property['type'] == 'StringProperty'), isTrue); }); test('filterProperties - replace', () { @@ -154,7 +154,7 @@ void main() { ]; }, )); - final List> properties = result['properties']! as List>; + final List> properties = result['properties']! as List>; expect(properties, hasLength(1)); expect(properties.single['name'], 'foo'); }); @@ -166,7 +166,7 @@ void main() { return nodes.where((DiagnosticsNode node) => node.getProperties().isEmpty).toList(); }, )); - final List> children = result['children']! as List>; + final List> children = result['children']! as List>; expect(children, hasLength(1)); }); @@ -177,7 +177,7 @@ void main() { return nodes.expand((DiagnosticsNode node) => node.getChildren()).toList(); }, )); - final List> children = result['children']! as List>; + final List> children = result['children']! as List>; expect(children, hasLength(3)); expect(children.first['name'], 'child node B1'); }); @@ -190,11 +190,11 @@ void main() { return nodes.take(2).toList(); }, )); - final List> children = result['children']! as List>; + final List> children = result['children']! as List>; expect(children, hasLength(3)); expect(children.last['truncated'], isTrue); - final List> properties = result['properties']! as List>; + final List> properties = result['properties']! as List>; expect(properties, hasLength(3)); expect(properties.last['truncated'], isTrue); }); @@ -207,13 +207,13 @@ void main() { return delegate.copyWith(includeProperties: false); }, )); - final List> properties = result['properties']! as List>; + final List> properties = result['properties']! as List>; expect(properties, hasLength(7)); - expect(properties.every((Map property) => !property.containsKey('properties')), isTrue); + expect(properties.every((Map property) => !property.containsKey('properties')), isTrue); - final List> children = result['children']! as List>; + final List> children = result['children']! as List>; expect(children, hasLength(3)); - expect(children.every((Map child) => !child.containsKey('properties')), isTrue); + expect(children.every((Map child) => !child.containsKey('properties')), isTrue); }); }); } diff --git a/packages/flutter/test/foundation/diagnostics_test.dart b/packages/flutter/test/foundation/diagnostics_test.dart index fea0b46a7c..a6cef4d934 100644 --- a/packages/flutter/test/foundation/diagnostics_test.dart +++ b/packages/flutter/test/foundation/diagnostics_test.dart @@ -47,15 +47,15 @@ enum ExampleEnum { /// Encode and decode to JSON to make sure all objects in the JSON for the /// [DiagnosticsNode] are valid JSON. -Map simulateJsonSerialization(DiagnosticsNode node) { - return json.decode(json.encode(node.toJsonMap(const DiagnosticsSerializationDelegate()))) as Map; +Map simulateJsonSerialization(DiagnosticsNode node) { + return json.decode(json.encode(node.toJsonMap(const DiagnosticsSerializationDelegate()))) as Map; } void validateNodeJsonSerialization(DiagnosticsNode node) { validateNodeJsonSerializationHelper(simulateJsonSerialization(node), node); } -void validateNodeJsonSerializationHelper(Map json, DiagnosticsNode node) { +void validateNodeJsonSerializationHelper(Map json, DiagnosticsNode node) { expect(json['name'], equals(node.name)); expect(json['showSeparator'] ?? true, equals(node.showSeparator)); expect(json['description'], equals(node.toDescription())); @@ -67,18 +67,18 @@ void validateNodeJsonSerializationHelper(Map json, DiagnosticsNo expect(json['hasChildren'] ?? false, equals(node.getChildren().isNotEmpty)); } -void validatePropertyJsonSerialization(DiagnosticsProperty property) { +void validatePropertyJsonSerialization(DiagnosticsProperty property) { validatePropertyJsonSerializationHelper(simulateJsonSerialization(property), property); } void validateStringPropertyJsonSerialization(StringProperty property) { - final Map json = simulateJsonSerialization(property); + final Map json = simulateJsonSerialization(property); expect(json['quoted'], equals(property.quoted)); validatePropertyJsonSerializationHelper(json, property); } void validateFlagPropertyJsonSerialization(FlagProperty property) { - final Map json = simulateJsonSerialization(property); + final Map json = simulateJsonSerialization(property); expect(json['ifTrue'], equals(property.ifTrue)); if (property.ifTrue != null) { @@ -96,7 +96,7 @@ void validateFlagPropertyJsonSerialization(FlagProperty property) { } void validateDoublePropertyJsonSerialization(DoubleProperty property) { - final Map json = simulateJsonSerialization(property); + final Map json = simulateJsonSerialization(property); if (property.unit != null) { expect(json['unit'], equals(property.unit)); } else { @@ -109,7 +109,7 @@ void validateDoublePropertyJsonSerialization(DoubleProperty property) { } void validateObjectFlagPropertyJsonSerialization(ObjectFlagProperty property) { - final Map json = simulateJsonSerialization(property); + final Map json = simulateJsonSerialization(property); if (property.ifPresent != null) { expect(json['ifPresent'], equals(property.ifPresent)); } else { @@ -120,7 +120,7 @@ void validateObjectFlagPropertyJsonSerialization(ObjectFlagProperty prop } void validateIterableFlagsPropertyJsonSerialization(FlagsSummary property) { - final Map json = simulateJsonSerialization(property); + final Map json = simulateJsonSerialization(property); if (property.value.isNotEmpty) { expect(json['values'], equals( property.value.entries @@ -135,9 +135,9 @@ void validateIterableFlagsPropertyJsonSerialization(FlagsSummary proper } void validateIterablePropertyJsonSerialization(IterableProperty property) { - final Map json = simulateJsonSerialization(property); + final Map json = simulateJsonSerialization(property); if (property.value != null) { - final List valuesJson = json['values']! as List; + final List valuesJson = json['values']! as List; final List expectedValues = property.value!.map((Object value) => value.toString()).toList(); expect(listEquals(valuesJson, expectedValues), isTrue); } else { @@ -147,7 +147,7 @@ void validateIterablePropertyJsonSerialization(IterableProperty property validatePropertyJsonSerializationHelper(json, property); } -void validatePropertyJsonSerializationHelper(final Map json, DiagnosticsProperty property) { +void validatePropertyJsonSerializationHelper(final Map json, DiagnosticsProperty property) { if (property.defaultValue != kNoDefaultValue) { expect(json['defaultValue'], equals(property.defaultValue.toString())); } else { @@ -1919,7 +1919,7 @@ void main() { expect(messageProperty.name, equals('diagnostics')); expect(messageProperty.value, isNull); expect(messageProperty.showName, isTrue); - validatePropertyJsonSerialization(messageProperty as DiagnosticsProperty); + validatePropertyJsonSerialization(messageProperty as DiagnosticsProperty); }); test('error message style wrap test', () { @@ -2246,7 +2246,7 @@ void main() { test('DiagnosticsProperty for basic types has value in json', () { DiagnosticsProperty intProperty = DiagnosticsProperty('int1', 10); - Map json = simulateJsonSerialization(intProperty); + Map json = simulateJsonSerialization(intProperty); expect(json['name'], 'int1'); expect(json['value'], 10); diff --git a/packages/flutter/test/material/app_test.dart b/packages/flutter/test/material/app_test.dart index 428af5e729..46fbcecf0c 100644 --- a/packages/flutter/test/material/app_test.dart +++ b/packages/flutter/test/material/app_test.dart @@ -249,7 +249,7 @@ void main() { }); testWidgets('Return value from pop is correct', (WidgetTester tester) async { - late Future result; + late Future result; await tester.pumpWidget( MaterialApp( home: Builder( @@ -258,7 +258,7 @@ void main() { child: ElevatedButton( child: const Text('X'), onPressed: () async { - result = Navigator.of(context)!.pushNamed('/a'); + result = Navigator.of(context)!.pushNamed('/a'); }, ), ); diff --git a/packages/flutter/test/material/date_picker_test.dart b/packages/flutter/test/material/date_picker_test.dart index b1ea26e0de..e135d5620f 100644 --- a/packages/flutter/test/material/date_picker_test.dart +++ b/packages/flutter/test/material/date_picker_test.dart @@ -83,7 +83,7 @@ void main() { Future prepareDatePicker( WidgetTester tester, - Future callback(Future date), + Future callback(Future date), { TextDirection textDirection = TextDirection.ltr } ) async { late BuildContext buttonContext; @@ -105,7 +105,7 @@ void main() { await tester.tap(find.text('Go')); expect(buttonContext, isNotNull); - final Future date = showDatePicker( + final Future date = showDatePicker( context: buttonContext, initialDate: initialDate, firstDate: firstDate, @@ -138,7 +138,7 @@ void main() { cancelText = 'nope'; confirmText = 'yep'; helpText = 'help'; - await prepareDatePicker(tester, (Future date) async { + await prepareDatePicker(tester, (Future date) async { expect(find.text(cancelText!), findsOneWidget); expect(find.text(confirmText!), findsOneWidget); expect(find.text(helpText!), findsOneWidget); @@ -146,21 +146,21 @@ void main() { }); testWidgets('Initial date is the default', (WidgetTester tester) async { - await prepareDatePicker(tester, (Future date) async { + await prepareDatePicker(tester, (Future date) async { await tester.tap(find.text('OK')); expect(await date, DateTime(2016, DateTime.january, 15)); }); }); testWidgets('Can cancel', (WidgetTester tester) async { - await prepareDatePicker(tester, (Future date) async { + await prepareDatePicker(tester, (Future date) async { await tester.tap(find.text('CANCEL')); expect(await date, isNull); }); }); testWidgets('Can toggle to input entry mode', (WidgetTester tester) async { - await prepareDatePicker(tester, (Future date) async { + await prepareDatePicker(tester, (Future date) async { expect(find.byType(TextField), findsNothing); await tester.tap(find.byIcon(Icons.edit)); await tester.pumpAndSettle(); @@ -169,7 +169,7 @@ void main() { }); testWidgets('Toggle to input mode keeps selected date', (WidgetTester tester) async { - await prepareDatePicker(tester, (Future date) async { + await prepareDatePicker(tester, (Future date) async { await tester.tap(find.text('12')); await tester.tap(find.byIcon(Icons.edit)); await tester.pumpAndSettle(); @@ -179,7 +179,7 @@ void main() { }); testWidgets('Switching to input mode resets input error state', (WidgetTester tester) async { - await prepareDatePicker(tester, (Future date) async { + await prepareDatePicker(tester, (Future date) async { // Enter text input mode and type an invalid date to get error. await tester.tap(find.byIcon(Icons.edit)); await tester.pumpAndSettle(); @@ -438,7 +438,7 @@ void main() { group('Calendar mode', () { testWidgets('Can select a day', (WidgetTester tester) async { - await prepareDatePicker(tester, (Future date) async { + await prepareDatePicker(tester, (Future date) async { await tester.tap(find.text('12')); await tester.tap(find.text('OK')); expect(await date, equals(DateTime(2016, DateTime.january, 12))); @@ -446,7 +446,7 @@ void main() { }); testWidgets('Can select a month', (WidgetTester tester) async { - await prepareDatePicker(tester, (Future date) async { + await prepareDatePicker(tester, (Future date) async { await tester.tap(previousMonthIcon); await tester.pumpAndSettle(const Duration(seconds: 1)); await tester.tap(find.text('25')); @@ -456,7 +456,7 @@ void main() { }); testWidgets('Can select a year', (WidgetTester tester) async { - await prepareDatePicker(tester, (Future date) async { + await prepareDatePicker(tester, (Future date) async { await tester.tap(find.text('January 2016')); // Switch to year mode. await tester.pump(); await tester.tap(find.text('2018')); @@ -467,7 +467,7 @@ void main() { testWidgets('Selecting date does not change displayed month', (WidgetTester tester) async { initialDate = DateTime(2020, DateTime.march, 15); - await prepareDatePicker(tester, (Future date) async { + await prepareDatePicker(tester, (Future date) async { await tester.tap(nextMonthIcon); await tester.pumpAndSettle(const Duration(seconds: 1)); expect(find.text('April 2020'), findsOneWidget); @@ -480,7 +480,7 @@ void main() { }); testWidgets('Changing year does not change selected date', (WidgetTester tester) async { - await prepareDatePicker(tester, (Future date) async { + await prepareDatePicker(tester, (Future date) async { await tester.tap(find.text('January 2016')); await tester.pump(); await tester.tap(find.text('2018')); @@ -491,7 +491,7 @@ void main() { }); testWidgets('Changing year does not change the month', (WidgetTester tester) async { - await prepareDatePicker(tester, (Future date) async { + await prepareDatePicker(tester, (Future date) async { await tester.tap(nextMonthIcon); await tester.pumpAndSettle(); await tester.tap(nextMonthIcon); @@ -505,7 +505,7 @@ void main() { }); testWidgets('Can select a year and then a day', (WidgetTester tester) async { - await prepareDatePicker(tester, (Future date) async { + await prepareDatePicker(tester, (Future date) async { await tester.tap(find.text('January 2016')); // Switch to year mode. await tester.pump(); await tester.tap(find.text('2017')); @@ -517,7 +517,7 @@ void main() { }); testWidgets('Current year is visible in year picker', (WidgetTester tester) async { - await prepareDatePicker(tester, (Future date) async { + await prepareDatePicker(tester, (Future date) async { await tester.tap(find.text('January 2016')); // Switch to year mode. await tester.pump(); expect(find.text('2016'), findsOneWidget); @@ -528,7 +528,7 @@ void main() { initialDate = DateTime(2017, DateTime.january, 15); firstDate = initialDate; lastDate = initialDate; - await prepareDatePicker(tester, (Future date) async { + await prepareDatePicker(tester, (Future date) async { // Earlier than firstDate. Should be ignored. await tester.tap(find.text('10')); // Later than lastDate. Should be ignored. @@ -543,7 +543,7 @@ void main() { initialDate = DateTime(2017, DateTime.january, 15); firstDate = initialDate; lastDate = DateTime(2017, DateTime.february, 20); - await prepareDatePicker(tester, (Future date) async { + await prepareDatePicker(tester, (Future date) async { await tester.tap(nextMonthIcon); await tester.pumpAndSettle(const Duration(seconds: 1)); // Shouldn't be possible to keep going into March. @@ -555,7 +555,7 @@ void main() { initialDate = DateTime(2017, DateTime.january, 15); firstDate = DateTime(2016, DateTime.december, 10); lastDate = initialDate; - await prepareDatePicker(tester, (Future date) async { + await prepareDatePicker(tester, (Future date) async { await tester.tap(previousMonthIcon); await tester.pumpAndSettle(const Duration(seconds: 1)); // Shouldn't be possible to keep going into November. @@ -567,7 +567,7 @@ void main() { initialDate = DateTime(2018, DateTime.july, 4); firstDate = DateTime(2018, DateTime.june, 9); lastDate = DateTime(2018, DateTime.december, 15); - await prepareDatePicker(tester, (Future date) async { + await prepareDatePicker(tester, (Future date) async { await tester.tap(find.text('July 2018')); // Switch to year mode. await tester.pumpAndSettle(); await tester.tap(find.text('2016')); // Disabled, doesn't change the year. @@ -582,7 +582,7 @@ void main() { initialDate = DateTime(2018, DateTime.may, 4); firstDate = DateTime(2016, DateTime.june, 9); lastDate = DateTime(2019, DateTime.january, 15); - await prepareDatePicker(tester, (Future date) async { + await prepareDatePicker(tester, (Future date) async { await tester.tap(find.text('May 2018')); await tester.pumpAndSettle(); await tester.tap(find.text('2016')); @@ -596,7 +596,7 @@ void main() { initialDate = DateTime(2018, DateTime.may, 4); firstDate = DateTime(2016, DateTime.june, 9); lastDate = DateTime(2019, DateTime.january, 15); - await prepareDatePicker(tester, (Future date) async { + await prepareDatePicker(tester, (Future date) async { await tester.tap(find.text('May 2018')); await tester.pumpAndSettle(); await tester.tap(find.text('2019')); @@ -611,7 +611,7 @@ void main() { firstDate = DateTime(2017, DateTime.january, 10); lastDate = DateTime(2017, DateTime.january, 20); selectableDayPredicate = (DateTime day) => day.day.isEven; - await prepareDatePicker(tester, (Future date) async { + await prepareDatePicker(tester, (Future date) async { await tester.tap(find.text('13')); // Odd, doesn't work. await tester.tap(find.text('10')); // Even, works. await tester.tap(find.text('17')); // Odd, doesn't work. @@ -623,7 +623,7 @@ void main() { testWidgets('Can select initial calendar picker mode', (WidgetTester tester) async { initialDate = DateTime(2014, DateTime.january, 15); initialCalendarMode = DatePickerMode.year; - await prepareDatePicker(tester, (Future date) async { + await prepareDatePicker(tester, (Future date) async { await tester.pump(); // 2018 wouldn't be available if the year picker wasn't showing. // The initial current year is 2014. @@ -635,7 +635,7 @@ void main() { testWidgets('currentDate is highlighted', (WidgetTester tester) async { today = DateTime(2016, 1, 2); - await prepareDatePicker(tester, (Future date) async { + await prepareDatePicker(tester, (Future date) async { await tester.pump(); const Color todayColor = Color(0xff2196f3); // default primary color expect( @@ -649,7 +649,7 @@ void main() { testWidgets('Selecting date does not switch picker to year selection', (WidgetTester tester) async { initialDate = DateTime(2020, DateTime.may, 10); initialCalendarMode = DatePickerMode.year; - await prepareDatePicker(tester, (Future date) async { + await prepareDatePicker(tester, (Future date) async { await tester.pump(); await tester.tap(find.text('2017')); await tester.pump(); @@ -671,7 +671,7 @@ void main() { }); testWidgets('Initial entry mode is used', (WidgetTester tester) async { - await prepareDatePicker(tester, (Future date) async { + await prepareDatePicker(tester, (Future date) async { expect(find.byType(TextField), findsOneWidget); }); }); @@ -682,7 +682,7 @@ void main() { fieldHintText = 'hint'; fieldLabelText = 'label'; helpText = 'help'; - await prepareDatePicker(tester, (Future date) async { + await prepareDatePicker(tester, (Future date) async { expect(find.text(cancelText!), findsOneWidget); expect(find.text(confirmText!), findsOneWidget); expect(find.text(fieldHintText!), findsOneWidget); @@ -692,14 +692,14 @@ void main() { }); testWidgets('Initial date is the default', (WidgetTester tester) async { - await prepareDatePicker(tester, (Future date) async { + await prepareDatePicker(tester, (Future date) async { await tester.tap(find.text('OK')); expect(await date, DateTime(2016, DateTime.january, 15)); }); }); testWidgets('Can toggle to calendar entry mode', (WidgetTester tester) async { - await prepareDatePicker(tester, (Future date) async { + await prepareDatePicker(tester, (Future date) async { expect(find.byType(TextField), findsOneWidget); await tester.tap(find.byIcon(Icons.calendar_today)); await tester.pumpAndSettle(); @@ -708,7 +708,7 @@ void main() { }); testWidgets('Toggle to calendar mode keeps selected date', (WidgetTester tester) async { - await prepareDatePicker(tester, (Future date) async { + await prepareDatePicker(tester, (Future date) async { final TextField field = textField(tester); field.controller!.clear(); @@ -721,7 +721,7 @@ void main() { }); testWidgets('Entered text returns date', (WidgetTester tester) async { - await prepareDatePicker(tester, (Future date) async { + await prepareDatePicker(tester, (Future date) async { final TextField field = textField(tester); field.controller!.clear(); @@ -733,7 +733,7 @@ void main() { testWidgets('Too short entered text shows error', (WidgetTester tester) async { errorFormatText = 'oops'; - await prepareDatePicker(tester, (Future date) async { + await prepareDatePicker(tester, (Future date) async { final TextField field = textField(tester); field.controller!.clear(); @@ -749,7 +749,7 @@ void main() { testWidgets('Bad format entered text shows error', (WidgetTester tester) async { errorFormatText = 'oops'; - await prepareDatePicker(tester, (Future date) async { + await prepareDatePicker(tester, (Future date) async { final TextField field = textField(tester); field.controller!.clear(); @@ -766,7 +766,7 @@ void main() { testWidgets('Invalid entered text shows error', (WidgetTester tester) async { errorInvalidText = 'oops'; - await prepareDatePicker(tester, (Future date) async { + await prepareDatePicker(tester, (Future date) async { final TextField field = textField(tester); field.controller!.clear(); @@ -912,7 +912,7 @@ void main() { }); testWidgets('Selecting date vibrates', (WidgetTester tester) async { - await prepareDatePicker(tester, (Future date) async { + await prepareDatePicker(tester, (Future date) async { await tester.tap(find.text('10')); await tester.pump(hapticFeedbackInterval); expect(feedback.hapticCount, 1); @@ -926,7 +926,7 @@ void main() { }); testWidgets('Tapping unselectable date does not vibrate', (WidgetTester tester) async { - await prepareDatePicker(tester, (Future date) async { + await prepareDatePicker(tester, (Future date) async { await tester.tap(find.text('11')); await tester.pump(hapticFeedbackInterval); expect(feedback.hapticCount, 0); @@ -940,7 +940,7 @@ void main() { }); testWidgets('Changing modes and year vibrates', (WidgetTester tester) async { - await prepareDatePicker(tester, (Future date) async { + await prepareDatePicker(tester, (Future date) async { await tester.tap(find.text('January 2017')); await tester.pump(hapticFeedbackInterval); expect(feedback.hapticCount, 1); @@ -956,7 +956,7 @@ void main() { final SemanticsHandle semantics = tester.ensureSemantics(); addTearDown(semantics.dispose); - await prepareDatePicker(tester, (Future date) async { + await prepareDatePicker(tester, (Future date) async { // Header expect(tester.getSemantics(find.text('SELECT DATE')), matchesSemantics( label: 'SELECT DATE\nFri, Jan 15', @@ -1174,7 +1174,7 @@ void main() { addTearDown(semantics.dispose); initialCalendarMode = DatePickerMode.year; - await prepareDatePicker(tester, (Future date) async { + await prepareDatePicker(tester, (Future date) async { // Header expect(tester.getSemantics(find.text('SELECT DATE')), matchesSemantics( label: 'SELECT DATE\nFri, Jan 15', @@ -1231,7 +1231,7 @@ void main() { addTearDown(semantics.dispose); initialEntryMode = DatePickerEntryMode.input; - await prepareDatePicker(tester, (Future date) async { + await prepareDatePicker(tester, (Future date) async { // Header expect(tester.getSemantics(find.text('SELECT DATE')), matchesSemantics( label: 'SELECT DATE\nFri, Jan 15', @@ -1285,7 +1285,7 @@ void main() { group('Keyboard navigation', () { testWidgets('Can toggle to calendar entry mode', (WidgetTester tester) async { - await prepareDatePicker(tester, (Future date) async { + await prepareDatePicker(tester, (Future date) async { expect(find.byType(TextField), findsNothing); // Navigate to the entry toggle button and activate it await tester.sendKeyEvent(LogicalKeyboardKey.tab); @@ -1301,7 +1301,7 @@ void main() { }); testWidgets('Can toggle to year mode', (WidgetTester tester) async { - await prepareDatePicker(tester, (Future date) async { + await prepareDatePicker(tester, (Future date) async { expect(find.text('2016'), findsNothing); // Navigate to the year selector and activate it await tester.sendKeyEvent(LogicalKeyboardKey.tab); @@ -1313,7 +1313,7 @@ void main() { }); testWidgets('Can navigate next/previous months', (WidgetTester tester) async { - await prepareDatePicker(tester, (Future date) async { + await prepareDatePicker(tester, (Future date) async { expect(find.text('January 2016'), findsOneWidget); // Navigate to the previous month button and activate it twice await tester.sendKeyEvent(LogicalKeyboardKey.tab); @@ -1341,7 +1341,7 @@ void main() { }); testWidgets('Can navigate date grid with arrow keys', (WidgetTester tester) async { - await prepareDatePicker(tester, (Future date) async { + await prepareDatePicker(tester, (Future date) async { // Navigate to the grid await tester.sendKeyEvent(LogicalKeyboardKey.tab); await tester.sendKeyEvent(LogicalKeyboardKey.tab); @@ -1377,7 +1377,7 @@ void main() { }); testWidgets('Navigating with arrow keys scrolls months', (WidgetTester tester) async { - await prepareDatePicker(tester, (Future date) async { + await prepareDatePicker(tester, (Future date) async { // Navigate to the grid await tester.sendKeyEvent(LogicalKeyboardKey.tab); await tester.sendKeyEvent(LogicalKeyboardKey.tab); @@ -1425,7 +1425,7 @@ void main() { }); testWidgets('RTL text direction reverses the horizontal arrow key navigation', (WidgetTester tester) async { - await prepareDatePicker(tester, (Future date) async { + await prepareDatePicker(tester, (Future date) async { // Navigate to the grid await tester.sendKeyEvent(LogicalKeyboardKey.tab); await tester.sendKeyEvent(LogicalKeyboardKey.tab); @@ -1484,7 +1484,7 @@ void main() { addTearDown(tester.binding.window.clearPhysicalSizeTestValue); tester.binding.window.devicePixelRatioTestValue = 1.0; addTearDown(tester.binding.window.clearDevicePixelRatioTestValue); - await prepareDatePicker(tester, (Future date) async { + await prepareDatePicker(tester, (Future date) async { await tester.tap(find.text('OK')); }); await tester.pumpAndSettle(); diff --git a/packages/flutter/test/material/date_range_picker_test.dart b/packages/flutter/test/material/date_range_picker_test.dart index 8d1bb8a3c9..a8900219f2 100644 --- a/packages/flutter/test/material/date_range_picker_test.dart +++ b/packages/flutter/test/material/date_range_picker_test.dart @@ -52,7 +52,7 @@ void main() { Future preparePicker( WidgetTester tester, - Future callback(Future date), + Future callback(Future date), { TextDirection textDirection = TextDirection.ltr } ) async { late BuildContext buttonContext; @@ -74,7 +74,7 @@ void main() { await tester.tap(find.text('Go')); expect(buttonContext, isNotNull); - final Future range = showDateRangePicker( + final Future range = showDateRangePicker( context: buttonContext, initialDateRange: initialDateRange, firstDate: firstDate, @@ -107,14 +107,14 @@ void main() { testWidgets('Save and help text is used', (WidgetTester tester) async { helpText = 'help'; saveText = 'make it so'; - await preparePicker(tester, (Future range) async { + await preparePicker(tester, (Future range) async { expect(find.text(helpText!), findsOneWidget); expect(find.text(saveText!), findsOneWidget); }); }); testWidgets('Initial date is the default', (WidgetTester tester) async { - await preparePicker(tester, (Future range) async { + await preparePicker(tester, (Future range) async { await tester.tap(find.text('SAVE')); expect(await range, DateTimeRange( start: DateTime(2016, DateTime.january, 15), @@ -131,7 +131,7 @@ void main() { start: lastDate, end: lastDate, ); - await preparePicker(tester, (Future range) async { + await preparePicker(tester, (Future range) async { // December header should be showing, but no November expect(find.text('December 2016'), findsOneWidget); expect(find.text('November 2016'), findsNothing); @@ -146,7 +146,7 @@ void main() { start: firstDate, end: firstDate, ); - await preparePicker(tester, (Future range) async { + await preparePicker(tester, (Future range) async { // January and February headers should be showing, but no March expect(find.text('January 2015'), findsOneWidget); expect(find.text('February 2015'), findsOneWidget); @@ -161,7 +161,7 @@ void main() { currentDate = DateTime(2016, DateTime.september, 1); initialDateRange = null; - await preparePicker(tester, (Future range) async { + await preparePicker(tester, (Future range) async { // September and October headers should be showing, but no August expect(find.text('September 2016'), findsOneWidget); expect(find.text('October 2016'), findsOneWidget); @@ -170,14 +170,14 @@ void main() { }); testWidgets('Can cancel', (WidgetTester tester) async { - await preparePicker(tester, (Future range) async { + await preparePicker(tester, (Future range) async { await tester.tap(find.byIcon(Icons.close)); expect(await range, isNull); }); }); testWidgets('Can select a range', (WidgetTester tester) async { - await preparePicker(tester, (Future range) async { + await preparePicker(tester, (Future range) async { await tester.tap(find.text('12').first); await tester.tap(find.text('14').first); await tester.tap(find.text('SAVE')); @@ -189,7 +189,7 @@ void main() { }); testWidgets('Tapping earlier date resets selected range', (WidgetTester tester) async { - await preparePicker(tester, (Future range) async { + await preparePicker(tester, (Future range) async { await tester.tap(find.text('12').first); await tester.tap(find.text('11').first); await tester.tap(find.text('15').first); @@ -202,7 +202,7 @@ void main() { }); testWidgets('Can select single day range', (WidgetTester tester) async { - await preparePicker(tester, (Future range) async { + await preparePicker(tester, (Future range) async { await tester.tap(find.text('12').first); await tester.tap(find.text('12').first); await tester.tap(find.text('SAVE')); @@ -220,7 +220,7 @@ void main() { ); firstDate = DateTime(2017, DateTime.january, 12); lastDate = DateTime(2017, DateTime.january, 16); - await preparePicker(tester, (Future range) async { + await preparePicker(tester, (Future range) async { // Earlier than firstDate. Should be ignored. await tester.tap(find.text('10')); // Later than lastDate. Should be ignored. @@ -232,7 +232,7 @@ void main() { }); testWidgets('Can toggle to input entry mode', (WidgetTester tester) async { - await preparePicker(tester, (Future range) async { + await preparePicker(tester, (Future range) async { expect(find.byType(TextField), findsNothing); await tester.tap(find.byIcon(Icons.edit)); await tester.pumpAndSettle(); @@ -241,7 +241,7 @@ void main() { }); testWidgets('Toggle to input mode keeps selected date', (WidgetTester tester) async { - await preparePicker(tester, (Future range) async { + await preparePicker(tester, (Future range) async { await tester.tap(find.text('12').first); await tester.tap(find.text('14').first); await tester.tap(find.byIcon(Icons.edit)); @@ -262,7 +262,7 @@ void main() { testWidgets('Invalid start date', (WidgetTester tester) async { // Invalid start date should have neither a start nor end date selected in // calendar mode - await preparePicker(tester, (Future range) async { + await preparePicker(tester, (Future range) async { await tester.enterText(find.byType(TextField).at(0), '12/27/1918'); await tester.enterText(find.byType(TextField).at(1), '12/25/2016'); await tester.tap(find.byIcon(Icons.calendar_today)); @@ -275,7 +275,7 @@ void main() { testWidgets('Invalid end date', (WidgetTester tester) async { // Invalid end date should only have a start date selected - await preparePicker(tester, (Future range) async { + await preparePicker(tester, (Future range) async { await tester.enterText(find.byType(TextField).at(0), '12/24/2016'); await tester.enterText(find.byType(TextField).at(1), '12/25/2050'); await tester.tap(find.byIcon(Icons.calendar_today)); @@ -288,7 +288,7 @@ void main() { testWidgets('Invalid range', (WidgetTester tester) async { // Start date after end date should just use the start date - await preparePicker(tester, (Future range) async { + await preparePicker(tester, (Future range) async { await tester.enterText(find.byType(TextField).at(0), '12/25/2016'); await tester.enterText(find.byType(TextField).at(1), '12/24/2016'); await tester.tap(find.byIcon(Icons.calendar_today)); @@ -375,7 +375,7 @@ void main() { }); testWidgets('Selecting dates vibrates', (WidgetTester tester) async { - await preparePicker(tester, (Future range) async { + await preparePicker(tester, (Future range) async { await tester.tap(find.text('10').first); await tester.pump(hapticFeedbackInterval); expect(feedback.hapticCount, 1); @@ -389,7 +389,7 @@ void main() { }); testWidgets('Tapping unselectable date does not vibrate', (WidgetTester tester) async { - await preparePicker(tester, (Future range) async { + await preparePicker(tester, (Future range) async { await tester.tap(find.text('8').first); await tester.pump(hapticFeedbackInterval); expect(feedback.hapticCount, 0); @@ -399,7 +399,7 @@ void main() { group('Keyboard navigation', () { testWidgets('Can toggle to calendar entry mode', (WidgetTester tester) async { - await preparePicker(tester, (Future range) async { + await preparePicker(tester, (Future range) async { expect(find.byType(TextField), findsNothing); // Navigate to the entry toggle button and activate it await tester.sendKeyEvent(LogicalKeyboardKey.tab); @@ -412,7 +412,7 @@ void main() { }); testWidgets('Can navigate date grid with arrow keys', (WidgetTester tester) async { - await preparePicker(tester, (Future range) async { + await preparePicker(tester, (Future range) async { // Navigate to the grid await tester.sendKeyEvent(LogicalKeyboardKey.tab); await tester.sendKeyEvent(LogicalKeyboardKey.tab); @@ -464,7 +464,7 @@ void main() { }); testWidgets('Navigating with arrow keys scrolls as needed', (WidgetTester tester) async { - await preparePicker(tester, (Future range) async { + await preparePicker(tester, (Future range) async { // Jan and Feb headers should be showing, but no March expect(find.text('January 2016'), findsOneWidget); expect(find.text('February 2016'), findsOneWidget); @@ -529,7 +529,7 @@ void main() { }); testWidgets('RTL text direction reverses the horizontal arrow key navigation', (WidgetTester tester) async { - await preparePicker(tester, (Future range) async { + await preparePicker(tester, (Future range) async { // Navigate to the grid await tester.sendKeyEvent(LogicalKeyboardKey.tab); await tester.sendKeyEvent(LogicalKeyboardKey.tab); @@ -589,7 +589,7 @@ void main() { }); testWidgets('Initial entry mode is used', (WidgetTester tester) async { - await preparePicker(tester, (Future range) async { + await preparePicker(tester, (Future range) async { expect(find.byType(TextField), findsNWidgets(2)); }); }); @@ -603,7 +603,7 @@ void main() { fieldStartLabelText = 'label1'; fieldEndLabelText = 'label2'; helpText = 'help'; - await preparePicker(tester, (Future range) async { + await preparePicker(tester, (Future range) async { expect(find.text(cancelText!), findsOneWidget); expect(find.text(confirmText!), findsOneWidget); expect(find.text(fieldStartHintText!), findsOneWidget); @@ -615,7 +615,7 @@ void main() { }); testWidgets('Initial date is the default', (WidgetTester tester) async { - await preparePicker(tester, (Future range) async { + await preparePicker(tester, (Future range) async { await tester.tap(find.text('OK')); expect(await range, DateTimeRange( start: DateTime(2017, DateTime.january, 15), @@ -625,7 +625,7 @@ void main() { }); testWidgets('Can toggle to calendar entry mode', (WidgetTester tester) async { - await preparePicker(tester, (Future range) async { + await preparePicker(tester, (Future range) async { expect(find.byType(TextField), findsNWidgets(2)); await tester.tap(find.byIcon(Icons.calendar_today)); await tester.pumpAndSettle(); @@ -635,7 +635,7 @@ void main() { testWidgets('Toggle to calendar mode keeps selected date', (WidgetTester tester) async { initialDateRange = null; - await preparePicker(tester, (Future range) async { + await preparePicker(tester, (Future range) async { await tester.enterText(find.byType(TextField).at(0), '12/25/2016'); await tester.enterText(find.byType(TextField).at(1), '12/27/2016'); await tester.tap(find.byIcon(Icons.calendar_today)); @@ -651,7 +651,7 @@ void main() { testWidgets('Entered text returns range', (WidgetTester tester) async { initialDateRange = null; - await preparePicker(tester, (Future range) async { + await preparePicker(tester, (Future range) async { await tester.enterText(find.byType(TextField).at(0), '12/25/2016'); await tester.enterText(find.byType(TextField).at(1), '12/27/2016'); await tester.tap(find.text('OK')); @@ -666,7 +666,7 @@ void main() { testWidgets('Too short entered text shows error', (WidgetTester tester) async { initialDateRange = null; errorFormatText = 'oops'; - await preparePicker(tester, (Future range) async { + await preparePicker(tester, (Future range) async { await tester.enterText(find.byType(TextField).at(0), '12/25'); await tester.enterText(find.byType(TextField).at(1), '12/25'); expect(find.text(errorFormatText!), findsNothing); @@ -680,7 +680,7 @@ void main() { testWidgets('Bad format entered text shows error', (WidgetTester tester) async { initialDateRange = null; errorFormatText = 'oops'; - await preparePicker(tester, (Future range) async { + await preparePicker(tester, (Future range) async { await tester.enterText(find.byType(TextField).at(0), '20202014'); await tester.enterText(find.byType(TextField).at(1), '20212014'); expect(find.text(errorFormatText!), findsNothing); @@ -694,7 +694,7 @@ void main() { testWidgets('Invalid entered text shows error', (WidgetTester tester) async { initialDateRange = null; errorInvalidText = 'oops'; - await preparePicker(tester, (Future range) async { + await preparePicker(tester, (Future range) async { await tester.enterText(find.byType(TextField).at(0), '08/08/2014'); await tester.enterText(find.byType(TextField).at(1), '08/08/2014'); expect(find.text(errorInvalidText!), findsNothing); @@ -708,7 +708,7 @@ void main() { testWidgets('End before start date shows error', (WidgetTester tester) async { initialDateRange = null; errorInvalidRangeText = 'oops'; - await preparePicker(tester, (Future range) async { + await preparePicker(tester, (Future range) async { await tester.enterText(find.byType(TextField).at(0), '12/27/2016'); await tester.enterText(find.byType(TextField).at(1), '12/25/2016'); expect(find.text(errorInvalidRangeText!), findsNothing); @@ -722,7 +722,7 @@ void main() { testWidgets('Error text only displayed for invalid date', (WidgetTester tester) async { initialDateRange = null; errorInvalidText = 'oops'; - await preparePicker(tester, (Future range) async { + await preparePicker(tester, (Future range) async { await tester.enterText(find.byType(TextField).at(0), '12/27/2016'); await tester.enterText(find.byType(TextField).at(1), '01/01/2018'); expect(find.text(errorInvalidText!), findsNothing); @@ -735,7 +735,7 @@ void main() { testWidgets('End before start date does not get passed to calendar mode', (WidgetTester tester) async { initialDateRange = null; - await preparePicker(tester, (Future range) async { + await preparePicker(tester, (Future range) async { await tester.enterText(find.byType(TextField).at(0), '12/27/2016'); await tester.enterText(find.byType(TextField).at(1), '12/25/2016'); diff --git a/packages/flutter/test/material/dialog_test.dart b/packages/flutter/test/material/dialog_test.dart index cc54bbd587..212c499716 100644 --- a/packages/flutter/test/material/dialog_test.dart +++ b/packages/flutter/test/material/dialog_test.dart @@ -233,7 +233,7 @@ void main() { final BuildContext context = tester.element(find.text('Go')); - final Future result = showDialog( + final Future result = showDialog( context: context, builder: (BuildContext context) { return SimpleDialog( @@ -273,7 +273,7 @@ void main() { ), ); - final Future result = showDialog( + final Future result = showDialog( context: navigator.currentContext!, builder: (BuildContext context) { return SimpleDialog( @@ -1382,7 +1382,7 @@ void main() { final List dismissedItems = []; // Dismiss is confirmed IFF confirmDismiss() returns true. - Future confirmDismiss (DismissDirection dismissDirection) { + Future confirmDismiss (DismissDirection dismissDirection) async { return showDialog( context: _scaffoldKey.currentContext!, barrierDismissible: true, // showDialog() returns null if tapped outside the dialog @@ -1762,7 +1762,7 @@ void main() { final BuildContext context = tester.element(find.text('Go')); const RouteSettings exampleSetting = RouteSettings(name: 'simple'); - final Future result = showDialog( + final Future result = showDialog( context: context, builder: (BuildContext context) { return SimpleDialog( diff --git a/packages/flutter/test/material/popup_menu_test.dart b/packages/flutter/test/material/popup_menu_test.dart index 5347310c84..d4f5be8a96 100644 --- a/packages/flutter/test/material/popup_menu_test.dart +++ b/packages/flutter/test/material/popup_menu_test.dart @@ -465,7 +465,7 @@ void main() { final WidgetPredicate popupMenu = (Widget widget) { final String widgetType = widget.runtimeType.toString(); // TODO(mraleph): Remove the old case below. - return widgetType == '_PopupMenu' // normal case + return widgetType == '_PopupMenu' // normal case || widgetType == '_PopupMenu'; // for old versions of Dart that don't reify method type arguments }; @@ -794,7 +794,7 @@ void main() { await tester.pumpAndSettle(); // The position is different than the offset because the default position isn't at the origin. - expect(tester.getTopLeft(find.byWidgetPredicate((Widget w) => '${w.runtimeType}' == '_PopupMenu')), const Offset(364.0, 324.0)); + expect(tester.getTopLeft(find.byWidgetPredicate((Widget w) => '${w.runtimeType}' == '_PopupMenu')), const Offset(364.0, 324.0)); }); testWidgets('open PopupMenu has correct semantics', (WidgetTester tester) async { diff --git a/packages/flutter/test/material/search_test.dart b/packages/flutter/test/material/search_test.dart index fd73035470..9345317e93 100644 --- a/packages/flutter/test/material/search_test.dart +++ b/packages/flutter/test/material/search_test.dart @@ -80,7 +80,7 @@ void main() { // regression test for https://github.com/flutter/flutter/issues/18145 final _TestSearchDelegate delegate = _TestSearchDelegate(); - final List selectedResults = []; + final List selectedResults = []; await tester.pumpWidget(TestHomePage( delegate: delegate, @@ -105,7 +105,7 @@ void main() { await ServicesBinding.instance!.defaultBinaryMessenger.handlePlatformMessage('flutter/navigation', message, (_) { }); await tester.pumpAndSettle(); - expect(selectedResults, [null]); + expect(selectedResults, [null]); // We are on the homepage again expect(find.text('HomeBody'), findsOneWidget); @@ -374,7 +374,7 @@ void main() { }); testWidgets('Closing nested search returns to search', (WidgetTester tester) async { - final List nestedSearchResults = []; + final List nestedSearchResults = []; final _TestSearchDelegate nestedSearchDelegate = _TestSearchDelegate( suggestions: 'Nested Suggestions', result: 'Nested Result', @@ -389,7 +389,7 @@ void main() { tooltip: 'Nested Search', icon: const Icon(Icons.search), onPressed: () async { - final String result = await showSearch( + final String? result = await showSearch( context: context, delegate: nestedSearchDelegate, ); @@ -467,7 +467,7 @@ void main() { tooltip: 'Nested Search', icon: const Icon(Icons.search), onPressed: () async { - final String result = await showSearch( + final String? result = await showSearch( context: context, delegate: nestedSearchDelegate, ); @@ -702,7 +702,7 @@ class TestHomePage extends StatelessWidget { this.initialQuery, }) : super(key: key); - final List? results; + final List? results; final SearchDelegate delegate; final bool passInInitialQuery; final String? initialQuery; @@ -719,7 +719,7 @@ class TestHomePage extends StatelessWidget { tooltip: 'Search', icon: const Icon(Icons.search), onPressed: () async { - String selectedResult; + String? selectedResult; if (passInInitialQuery) { selectedResult = await showSearch( context: context, diff --git a/packages/flutter/test/material/time_picker_test.dart b/packages/flutter/test/material/time_picker_test.dart index 1296104142..cc13240745 100644 --- a/packages/flutter/test/material/time_picker_test.dart +++ b/packages/flutter/test/material/time_picker_test.dart @@ -23,7 +23,7 @@ class _TimePickerLauncher extends StatelessWidget { this.entryMode = TimePickerEntryMode.dial, }) : super(key: key); - final ValueChanged onChanged; + final ValueChanged onChanged; final Locale? locale; final TimePickerEntryMode entryMode; @@ -55,7 +55,7 @@ class _TimePickerLauncher extends StatelessWidget { Future startPicker( WidgetTester tester, - ValueChanged onChanged, { + ValueChanged onChanged, { TimePickerEntryMode entryMode = TimePickerEntryMode.dial, }) async { await tester.pumpWidget(_TimePickerLauncher(onChanged: onChanged, locale: const Locale('en', 'US'), entryMode: entryMode)); @@ -82,24 +82,24 @@ void main() { void _tests() { testWidgets('tap-select an hour', (WidgetTester tester) async { - late TimeOfDay result; + TimeOfDay? result; - Offset center = (await startPicker(tester, (TimeOfDay time) { result = time; }))!; + Offset center = (await startPicker(tester, (TimeOfDay? time) { result = time; }))!; await tester.tapAt(Offset(center.dx, center.dy - 50.0)); // 12:00 AM await finishPicker(tester); expect(result, equals(const TimeOfDay(hour: 0, minute: 0))); - center = (await startPicker(tester, (TimeOfDay time) { result = time; }))!; + center = (await startPicker(tester, (TimeOfDay? time) { result = time; }))!; await tester.tapAt(Offset(center.dx + 50.0, center.dy)); await finishPicker(tester); expect(result, equals(const TimeOfDay(hour: 3, minute: 0))); - center = (await startPicker(tester, (TimeOfDay time) { result = time; }))!; + center = (await startPicker(tester, (TimeOfDay? time) { result = time; }))!; await tester.tapAt(Offset(center.dx, center.dy + 50.0)); await finishPicker(tester); expect(result, equals(const TimeOfDay(hour: 6, minute: 0))); - center = (await startPicker(tester, (TimeOfDay time) { result = time; }))!; + center = (await startPicker(tester, (TimeOfDay? time) { result = time; }))!; await tester.tapAt(Offset(center.dx, center.dy + 50.0)); await tester.tapAt(Offset(center.dx - 50, center.dy)); await finishPicker(tester); @@ -109,7 +109,7 @@ void _tests() { testWidgets('drag-select an hour', (WidgetTester tester) async { late TimeOfDay result; - final Offset center = (await startPicker(tester, (TimeOfDay time) { result = time; }))!; + final Offset center = (await startPicker(tester, (TimeOfDay? time) { result = time!; }))!; final Offset hour0 = Offset(center.dx, center.dy - 50.0); // 12:00 AM final Offset hour3 = Offset(center.dx + 50.0, center.dy); final Offset hour6 = Offset(center.dx, center.dy + 50.0); @@ -123,21 +123,21 @@ void _tests() { await finishPicker(tester); expect(result.hour, 0); - expect(await startPicker(tester, (TimeOfDay time) { result = time; }), equals(center)); + expect(await startPicker(tester, (TimeOfDay? time) { result = time!; }), equals(center)); gesture = await tester.startGesture(hour0); await gesture.moveBy(hour3 - hour0); await gesture.up(); await finishPicker(tester); expect(result.hour, 3); - expect(await startPicker(tester, (TimeOfDay time) { result = time; }), equals(center)); + expect(await startPicker(tester, (TimeOfDay? time) { result = time!; }), equals(center)); gesture = await tester.startGesture(hour3); await gesture.moveBy(hour6 - hour3); await gesture.up(); await finishPicker(tester); expect(result.hour, equals(6)); - expect(await startPicker(tester, (TimeOfDay time) { result = time; }), equals(center)); + expect(await startPicker(tester, (TimeOfDay? time) { result = time!; }), equals(center)); gesture = await tester.startGesture(hour6); await gesture.moveBy(hour9 - hour6); await gesture.up(); @@ -148,7 +148,7 @@ void _tests() { testWidgets('tap-select switches from hour to minute', (WidgetTester tester) async { late TimeOfDay result; - final Offset center = (await startPicker(tester, (TimeOfDay time) { result = time; }))!; + final Offset center = (await startPicker(tester, (TimeOfDay? time) { result = time!; }))!; final Offset hour6 = Offset(center.dx, center.dy + 50.0); // 6:00 final Offset min45 = Offset(center.dx - 50.0, center.dy); // 45 mins (or 9:00 hours) @@ -162,7 +162,7 @@ void _tests() { testWidgets('drag-select switches from hour to minute', (WidgetTester tester) async { late TimeOfDay result; - final Offset center = (await startPicker(tester, (TimeOfDay time) { result = time; }))!; + final Offset center = (await startPicker(tester, (TimeOfDay? time) { result = time!; }))!; final Offset hour3 = Offset(center.dx + 50.0, center.dy); final Offset hour6 = Offset(center.dx, center.dy + 50.0); final Offset hour9 = Offset(center.dx - 50.0, center.dy); @@ -181,7 +181,7 @@ void _tests() { testWidgets('tap-select rounds down to nearest 5 minute increment', (WidgetTester tester) async { late TimeOfDay result; - final Offset center = (await startPicker(tester, (TimeOfDay time) { result = time; }))!; + final Offset center = (await startPicker(tester, (TimeOfDay? time) { result = time!; }))!; final Offset hour6 = Offset(center.dx, center.dy + 50.0); // 6:00 final Offset min46 = Offset(center.dx - 50.0, center.dy - 5); // 46 mins @@ -195,7 +195,7 @@ void _tests() { testWidgets('tap-select rounds up to nearest 5 minute increment', (WidgetTester tester) async { late TimeOfDay result; - final Offset center = (await startPicker(tester, (TimeOfDay time) { result = time; }))!; + final Offset center = (await startPicker(tester, (TimeOfDay? time) { result = time!; }))!; final Offset hour6 = Offset(center.dx, center.dy + 50.0); // 6:00 final Offset min48 = Offset(center.dx - 50.0, center.dy - 15); // 48 mins @@ -220,14 +220,14 @@ void _tests() { }); testWidgets('tap-select vibrates once', (WidgetTester tester) async { - final Offset center = (await startPicker(tester, (TimeOfDay time) { }))!; + final Offset center = (await startPicker(tester, (TimeOfDay? time) { }))!; await tester.tapAt(Offset(center.dx, center.dy - 50.0)); await finishPicker(tester); expect(feedback.hapticCount, 1); }); testWidgets('quick successive tap-selects vibrate once', (WidgetTester tester) async { - final Offset center = (await startPicker(tester, (TimeOfDay time) { }))!; + final Offset center = (await startPicker(tester, (TimeOfDay? time) { }))!; await tester.tapAt(Offset(center.dx, center.dy - 50.0)); await tester.pump(kFastFeedbackInterval); await tester.tapAt(Offset(center.dx, center.dy + 50.0)); @@ -236,7 +236,7 @@ void _tests() { }); testWidgets('slow successive tap-selects vibrate once per tap', (WidgetTester tester) async { - final Offset center = (await startPicker(tester, (TimeOfDay time) { }))!; + final Offset center = (await startPicker(tester, (TimeOfDay? time) { }))!; await tester.tapAt(Offset(center.dx, center.dy - 50.0)); await tester.pump(kSlowFeedbackInterval); await tester.tapAt(Offset(center.dx, center.dy + 50.0)); @@ -247,7 +247,7 @@ void _tests() { }); testWidgets('drag-select vibrates once', (WidgetTester tester) async { - final Offset center = (await startPicker(tester, (TimeOfDay time) { }))!; + final Offset center = (await startPicker(tester, (TimeOfDay? time) { }))!; final Offset hour0 = Offset(center.dx, center.dy - 50.0); final Offset hour3 = Offset(center.dx + 50.0, center.dy); @@ -259,7 +259,7 @@ void _tests() { }); testWidgets('quick drag-select vibrates once', (WidgetTester tester) async { - final Offset center = (await startPicker(tester, (TimeOfDay time) { }))!; + final Offset center = (await startPicker(tester, (TimeOfDay? time) { }))!; final Offset hour0 = Offset(center.dx, center.dy - 50.0); final Offset hour3 = Offset(center.dx + 50.0, center.dy); @@ -275,7 +275,7 @@ void _tests() { }); testWidgets('slow drag-select vibrates once', (WidgetTester tester) async { - final Offset center = (await startPicker(tester, (TimeOfDay time) { }))!; + final Offset center = (await startPicker(tester, (TimeOfDay? time) { }))!; final Offset hour0 = Offset(center.dx, center.dy - 50.0); final Offset hour3 = Offset(center.dx + 50.0, center.dy); @@ -794,7 +794,7 @@ void _testsInput() { testWidgets('Initial time is the default', (WidgetTester tester) async { late TimeOfDay result; - await startPicker(tester, (TimeOfDay time) { result = time; }, entryMode: TimePickerEntryMode.input); + await startPicker(tester, (TimeOfDay? time) { result = time!; }, entryMode: TimePickerEntryMode.input); await finishPicker(tester); expect(result, equals(const TimeOfDay(hour: 7, minute: 0))); }); @@ -898,7 +898,7 @@ void _testsInput() { testWidgets('Entered text returns time', (WidgetTester tester) async { late TimeOfDay result; - await startPicker(tester, (TimeOfDay time) { result = time; }, entryMode: TimePickerEntryMode.input); + await startPicker(tester, (TimeOfDay? time) { result = time!; }, entryMode: TimePickerEntryMode.input); await tester.enterText(find.byType(TextField).first, '9'); await tester.enterText(find.byType(TextField).last, '12'); await finishPicker(tester); @@ -907,7 +907,7 @@ void _testsInput() { testWidgets('Toggle to dial mode keeps selected time', (WidgetTester tester) async { late TimeOfDay result; - await startPicker(tester, (TimeOfDay time) { result = time; }, entryMode: TimePickerEntryMode.input); + await startPicker(tester, (TimeOfDay? time) { result = time!; }, entryMode: TimePickerEntryMode.input); await tester.enterText(find.byType(TextField).first, '8'); await tester.enterText(find.byType(TextField).last, '15'); await tester.tap(find.byIcon(Icons.access_time)); @@ -917,7 +917,7 @@ void _testsInput() { testWidgets('Invalid text prevents dismissing', (WidgetTester tester) async { TimeOfDay? result; - await startPicker(tester, (TimeOfDay time) { result = time; }, entryMode: TimePickerEntryMode.input); + await startPicker(tester, (TimeOfDay? time) { result = time; }, entryMode: TimePickerEntryMode.input); // Invalid hour. await tester.enterText(find.byType(TextField).first, '88'); @@ -939,7 +939,7 @@ void _testsInput() { // Fixes regression that was reverted in https://github.com/flutter/flutter/pull/64094#pullrequestreview-469836378. testWidgets('Ensure hour/minute fields are top-aligned with the separator', (WidgetTester tester) async { - await startPicker(tester, (TimeOfDay time) { }, entryMode: TimePickerEntryMode.input); + await startPicker(tester, (TimeOfDay? time) { }, entryMode: TimePickerEntryMode.input); final double hourFieldTop = tester.getTopLeft(find.byWidgetPredicate((Widget w) => '${w.runtimeType}' == '_HourTextField')).dy; final double minuteFieldTop = tester.getTopLeft(find.byWidgetPredicate((Widget w) => '${w.runtimeType}' == '_MinuteTextField')).dy; final double separatorTop = tester.getTopLeft(find.byWidgetPredicate((Widget w) => '${w.runtimeType}' == '_StringFragment')).dy; diff --git a/packages/flutter/test/material/will_pop_test.dart b/packages/flutter/test/material/will_pop_test.dart index c1c05a1bbd..9ff3c725d3 100644 --- a/packages/flutter/test/material/will_pop_test.dart +++ b/packages/flutter/test/material/will_pop_test.dart @@ -222,8 +222,8 @@ void main() { }); testWidgets('Form.willPop callbacks do not accumulate', (WidgetTester tester) async { - Future showYesNoAlert(BuildContext context) { - return showDialog( + Future showYesNoAlert(BuildContext context) async { + return (await showDialog( context: context, builder: (BuildContext context) { return AlertDialog( @@ -239,7 +239,7 @@ void main() { ], ); }, - ); + ))!; } Widget buildFrame() { diff --git a/packages/flutter/test/rendering/mock_canvas.dart b/packages/flutter/test/rendering/mock_canvas.dart index dceae4b7cf..c5165c7dbb 100644 --- a/packages/flutter/test/rendering/mock_canvas.dart +++ b/packages/flutter/test/rendering/mock_canvas.dart @@ -823,7 +823,6 @@ class _TestRecordingCanvasPatternMatcher extends _TestRecordingCanvasMatcher imp while (predicate.moveNext()) { predicate.current.match(call); } - assert(predicate.current == null); // We allow painting more than expected. } on _MismatchedCall catch (data) { description.writeln(data.message); diff --git a/packages/flutter/test/services/fake_platform_views.dart b/packages/flutter/test/services/fake_platform_views.dart index c105787c49..e91c93dae7 100644 --- a/packages/flutter/test/services/fake_platform_views.dart +++ b/packages/flutter/test/services/fake_platform_views.dart @@ -174,11 +174,11 @@ class FakeAndroidPlatformViewsController { final Map args = call.arguments as Map; final int id = args['id'] as int; final String viewType = args['viewType'] as String; - final double width = args['width'] as double; - final double height = args['height'] as double; + final double? width = args['width'] as double?; + final double? height = args['height'] as double?; final int layoutDirection = args['direction'] as int; - final bool hybrid = args['hybrid'] as bool; - final Uint8List creationParams = args['params'] as Uint8List; + final bool? hybrid = args['hybrid'] as bool?; + final Uint8List? creationParams = args['params'] as Uint8List?; if (_views.containsKey(id)) throw PlatformException( @@ -197,7 +197,7 @@ class FakeAndroidPlatformViewsController { } _views[id] = FakeAndroidPlatformView(id, viewType, - width != null || height != null ? Size(width, height) : null, + width != null && height != null ? Size(width, height) : null, layoutDirection, hybrid, creationParams, @@ -344,7 +344,7 @@ class FakeIosPlatformViewsController { final Map args = call.arguments as Map; final int id = args['id'] as int; final String viewType = args['viewType'] as String; - final Uint8List creationParams = args['params'] as Uint8List; + final Uint8List? creationParams = args['params'] as Uint8List?; if (_views.containsKey(id)) { throw PlatformException( diff --git a/packages/flutter/test/services/platform_views_test.dart b/packages/flutter/test/services/platform_views_test.dart index 1db8c6adcb..d4386920c2 100644 --- a/packages/flutter/test/services/platform_views_test.dart +++ b/packages/flutter/test/services/platform_views_test.dart @@ -2,7 +2,6 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. - import 'package:flutter/painting.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart' show TestWidgetsFlutterBinding; diff --git a/packages/flutter/test/widgets/custom_paint_test.dart b/packages/flutter/test/widgets/custom_paint_test.dart index 24e2d3a816..68013a3498 100644 --- a/packages/flutter/test/widgets/custom_paint_test.dart +++ b/packages/flutter/test/widgets/custom_paint_test.dart @@ -58,7 +58,7 @@ class MockPaintingContext extends Fake implements PaintingContext { void main() { testWidgets('Control test for custom painting', (WidgetTester tester) async { - final List log = []; + final List log = []; await tester.pumpWidget(CustomPaint( painter: TestCustomPainter( log: log, @@ -82,7 +82,7 @@ void main() { testWidgets('Throws FlutterError on custom painter incorrect restore/save calls', ( WidgetTester tester) async { final GlobalKey target = GlobalKey(); - final List log = []; + final List log = []; await tester.pumpWidget(CustomPaint( key: target, isComplex: true, @@ -174,7 +174,7 @@ void main() { testWidgets('Raster cache hints', (WidgetTester tester) async { final GlobalKey target = GlobalKey(); - final List log = []; + final List log = []; await tester.pumpWidget(CustomPaint( key: target, isComplex: true, diff --git a/packages/flutter/test/widgets/dismissible_test.dart b/packages/flutter/test/widgets/dismissible_test.dart index 1589ad9490..1ac1732385 100644 --- a/packages/flutter/test/widgets/dismissible_test.dart +++ b/packages/flutter/test/widgets/dismissible_test.dart @@ -18,7 +18,7 @@ const double crossAxisEndOffset = 0.5; Widget buildTest({ double? startToEndThreshold, TextDirection textDirection = TextDirection.ltr, - Future Function(BuildContext context, DismissDirection direction)? confirmDismiss, + Future Function(BuildContext context, DismissDirection direction)? confirmDismiss, }) { return Directionality( textDirection: textDirection, @@ -679,7 +679,7 @@ void main() { return buildTest( confirmDismiss: (BuildContext context, DismissDirection dismissDirection) { confirmDismissDirection = dismissDirection; - return Future.value(confirmDismissValue); + return Future.value(confirmDismissValue); } ); } diff --git a/packages/flutter/test/widgets/image_test.dart b/packages/flutter/test/widgets/image_test.dart index b45b963b01..1046e02550 100644 --- a/packages/flutter/test/widgets/image_test.dart +++ b/packages/flutter/test/widgets/image_test.dart @@ -1516,7 +1516,7 @@ void main() { expect(imageCache!.liveImageCount, 1); expect(imageCache!.containsKey(provider), false); - final ImageCacheStatus providerLocation = await provider.obtainCacheStatus(configuration: ImageConfiguration.empty); + final ImageCacheStatus providerLocation = (await provider.obtainCacheStatus(configuration: ImageConfiguration.empty))!; expect(providerLocation, isNotNull); expect(providerLocation.live, true); diff --git a/packages/flutter/test/widgets/navigator_test.dart b/packages/flutter/test/widgets/navigator_test.dart index d0de31e14e..a08d14bf20 100644 --- a/packages/flutter/test/widgets/navigator_test.dart +++ b/packages/flutter/test/widgets/navigator_test.dart @@ -957,7 +957,7 @@ void main() { }); testWidgets('replaceNamed returned value', (WidgetTester tester) async { - late Future value; + late Future value; final Map routes = { '/' : (BuildContext context) => OnTapPage(id: '/', onTap: () { Navigator.pushNamed(context, '/A'); }), @@ -1001,7 +1001,7 @@ void main() { expect(find.text('A'), findsNothing); expect(find.text('B'), findsNothing); - final String replaceNamedValue = await value; // replaceNamed result was 'B' + final String? replaceNamedValue = await value; // replaceNamed result was 'B' expect(replaceNamedValue, 'B'); }); @@ -1092,7 +1092,7 @@ void main() { }); testWidgets('remove a route whose value is awaited', (WidgetTester tester) async { - late Future pageValue; + late Future pageValue; final Map pageBuilders = { '/': (BuildContext context) => OnTapPage(id: '/', onTap: () { pageValue = Navigator.pushNamed(context, '/A'); }), '/A': (BuildContext context) => OnTapPage(id: 'A', onTap: () { Navigator.pop(context, 'A'); }), @@ -1113,7 +1113,7 @@ void main() { await tester.tap(find.text('/')); // pushNamed('/A'), stack becomes /, /A await tester.pumpAndSettle(); - pageValue.then((String value) { assert(false); }); + pageValue.then((String? value) { assert(false); }); final NavigatorState navigator = tester.state(find.byType(Navigator)); navigator.removeRoute(routes['/A']!); // stack becomes /, pageValue will not complete diff --git a/packages/flutter/test/widgets/restorable_property_test.dart b/packages/flutter/test/widgets/restorable_property_test.dart index fa6396253c..85a10de0f8 100644 --- a/packages/flutter/test/widgets/restorable_property_test.dart +++ b/packages/flutter/test/widgets/restorable_property_test.dart @@ -285,7 +285,7 @@ void main() { }); } -class _TestRestorableValue extends RestorableValue { +class _TestRestorableValue extends RestorableValue { @override Object createDefaultValue() { return 55; @@ -300,12 +300,12 @@ class _TestRestorableValue extends RestorableValue { } @override - Object fromPrimitives(Object data) { + Object? fromPrimitives(Object? data) { return data; } @override - Object toPrimitives() { + Object? toPrimitives() { return value; } } diff --git a/packages/flutter/test/widgets/restoration_mixin_test.dart b/packages/flutter/test/widgets/restoration_mixin_test.dart index 8e0ff5d783..f44348d08e 100644 --- a/packages/flutter/test/widgets/restoration_mixin_test.dart +++ b/packages/flutter/test/widgets/restoration_mixin_test.dart @@ -632,7 +632,7 @@ void main() { }); test('RestorableProperty throws after disposed', () { - final RestorableProperty property = _TestRestorableProperty(10); + final RestorableProperty property = _TestRestorableProperty(10); property.dispose(); expect(() => property.dispose(), throwsFlutterError); }); @@ -660,8 +660,8 @@ class _TestRestorableWidgetState extends State<_TestRestorableWidget> with Resto _TestRestorableProperty? additionalProperty; bool _rerigisterAdditionalProperty = false; - final List restoreStateLog = []; - final List toggleBucketLog = []; + final List restoreStateLog = []; + final List toggleBucketLog = []; @override void restoreState(RestorationBucket? oldBucket, bool initialRestore) { @@ -737,7 +737,7 @@ Map _createRawDataSet() { }; } -class _TestRestorableProperty extends RestorableProperty { +class _TestRestorableProperty extends RestorableProperty { _TestRestorableProperty(this._value); List log = []; @@ -751,35 +751,35 @@ class _TestRestorableProperty extends RestorableProperty { } @override - Object createDefaultValue() { + Object? createDefaultValue() { log.add('createDefaultValue'); return _value; } @override - Object fromPrimitives(Object data) { + Object? fromPrimitives(Object? data) { log.add('fromPrimitives'); return data; } - Object get value { + Object? get value { assert(isRegistered); return _value; } - Object _value; - set value(Object value) { + Object? _value; + set value(Object? value) { _value = value; notifyListeners(); } @override - void initWithValue(Object v) { + void initWithValue(Object? v) { log.add('initWithValue'); _value = v; } @override - Object toPrimitives() { + Object? toPrimitives() { log.add('toPrimitives'); return _value; } diff --git a/packages/flutter/test/widgets/restoration_scopes_moving_test.dart b/packages/flutter/test/widgets/restoration_scopes_moving_test.dart index 3c07df3870..cac9033cca 100644 --- a/packages/flutter/test/widgets/restoration_scopes_moving_test.dart +++ b/packages/flutter/test/widgets/restoration_scopes_moving_test.dart @@ -209,7 +209,7 @@ class TestWidget extends StatefulWidget { } class TestWidgetState extends State with RestorationMixin { - List buckets = []; + List buckets = []; List flags = []; @override diff --git a/packages/flutter/test/widgets/root_restoration_scope_test.dart b/packages/flutter/test/widgets/root_restoration_scope_test.dart index 85d57ce314..4a090202cc 100644 --- a/packages/flutter/test/widgets/root_restoration_scope_test.dart +++ b/packages/flutter/test/widgets/root_restoration_scope_test.dart @@ -302,7 +302,7 @@ void main() { }); testWidgets('injects null when rootBucket is null', (WidgetTester tester) async { - final Completer completer = Completer(); + final Completer completer = Completer(); binding.restorationManager.rootBucket = completer.future; await tester.pumpWidget( diff --git a/packages/flutter/test/widgets/routes_test.dart b/packages/flutter/test/widgets/routes_test.dart index 2fd08a323a..b5fdfb8df3 100644 --- a/packages/flutter/test/widgets/routes_test.dart +++ b/packages/flutter/test/widgets/routes_test.dart @@ -1319,28 +1319,28 @@ void main() { final Finder animatedModalBarrier = find.byType(AnimatedModalBarrier); expect(animatedModalBarrier, findsOneWidget); - Animation modalBarrierAnimation; + Animation modalBarrierAnimation; modalBarrierAnimation = tester.widget(animatedModalBarrier).color; expect(modalBarrierAnimation.value, Colors.transparent); await tester.pump(const Duration(milliseconds: 25)); modalBarrierAnimation = tester.widget(animatedModalBarrier).color; expect( - modalBarrierAnimation.value.alpha, + modalBarrierAnimation.value!.alpha, closeTo(_getExpectedBarrierTweenAlphaValue(0.25), 1), ); await tester.pump(const Duration(milliseconds: 25)); modalBarrierAnimation = tester.widget(animatedModalBarrier).color; expect( - modalBarrierAnimation.value.alpha, + modalBarrierAnimation.value!.alpha, closeTo(_getExpectedBarrierTweenAlphaValue(0.50), 1), ); await tester.pump(const Duration(milliseconds: 25)); modalBarrierAnimation = tester.widget(animatedModalBarrier).color; expect( - modalBarrierAnimation.value.alpha, + modalBarrierAnimation.value!.alpha, closeTo(_getExpectedBarrierTweenAlphaValue(0.75), 1), ); @@ -1382,28 +1382,28 @@ void main() { final Finder animatedModalBarrier = find.byType(AnimatedModalBarrier); expect(animatedModalBarrier, findsOneWidget); - Animation modalBarrierAnimation; + Animation modalBarrierAnimation; modalBarrierAnimation = tester.widget(animatedModalBarrier).color; expect(modalBarrierAnimation.value, Colors.transparent); await tester.pump(const Duration(milliseconds: 25)); modalBarrierAnimation = tester.widget(animatedModalBarrier).color; expect( - modalBarrierAnimation.value.alpha, + modalBarrierAnimation.value!.alpha, closeTo(_getExpectedBarrierTweenAlphaValue(0.25), 1), ); await tester.pump(const Duration(milliseconds: 25)); modalBarrierAnimation = tester.widget(animatedModalBarrier).color; expect( - modalBarrierAnimation.value.alpha, + modalBarrierAnimation.value!.alpha, closeTo(_getExpectedBarrierTweenAlphaValue(0.50), 1), ); await tester.pump(const Duration(milliseconds: 25)); modalBarrierAnimation = tester.widget(animatedModalBarrier).color; expect( - modalBarrierAnimation.value.alpha, + modalBarrierAnimation.value!.alpha, closeTo(_getExpectedBarrierTweenAlphaValue(0.75), 1), ); diff --git a/packages/flutter_test/lib/src/_matchers_io.dart b/packages/flutter_test/lib/src/_matchers_io.dart index 9c1f02244d..80d6919d8d 100644 --- a/packages/flutter_test/lib/src/_matchers_io.dart +++ b/packages/flutter_test/lib/src/_matchers_io.dart @@ -49,27 +49,31 @@ class MatchesGoldenFile extends AsyncMatcher { @override Future matchAsync(dynamic item) async { - Future imageFuture; - if (item is Future) { + Future imageFuture; + if (item is Future) { imageFuture = item; } else if (item is ui.Image) { imageFuture = Future.value(item); - } else { - final Finder finder = item as Finder; - final Iterable elements = finder.evaluate(); + } else if (item is Finder) { + final Iterable elements = item.evaluate(); if (elements.isEmpty) { return 'could not be rendered because no widget was found'; } else if (elements.length > 1) { return 'matched too many widgets'; } imageFuture = captureImage(elements.single); + } else { + throw 'must provide a Finder, Image, or Future'; } final Uri testNameUri = goldenFileComparator.getTestUri(key, version); final TestWidgetsFlutterBinding binding = TestWidgetsFlutterBinding.ensureInitialized() as TestWidgetsFlutterBinding; return binding.runAsync(() async { - final ui.Image image = await imageFuture; + final ui.Image? image = await imageFuture; + if (image == null) { + throw 'Future completed to null'; + } final ByteData? bytes = await image.toByteData(format: ui.ImageByteFormat.png); if (bytes == null) return 'could not encode screenshot.'; diff --git a/packages/flutter_test/lib/src/binding.dart b/packages/flutter_test/lib/src/binding.dart index 0b76a0b988..116746abf5 100644 --- a/packages/flutter_test/lib/src/binding.dart +++ b/packages/flutter_test/lib/src/binding.dart @@ -1011,17 +1011,19 @@ class AutomatedTestWidgetsFlutterBinding extends TestWidgetsFlutterBinding { addTime(additionalTime); - return realAsyncZone.run>(() { + return realAsyncZone.run>(() async { _pendingAsyncTasks = Completer(); - return callback().catchError((Object exception, StackTrace stack) { + T? result; + try { + result = await callback(); + } catch (exception, stack) { FlutterError.reportError(FlutterErrorDetails( exception: exception, stack: stack, library: 'Flutter test framework', context: ErrorDescription('while running async test code'), )); - return null; - }).whenComplete(() { + } finally { // We complete the _pendingAsyncTasks future successfully regardless of // whether an exception occurred because in the case of an exception, // we already reported the exception to FlutterError. Moreover, @@ -1029,7 +1031,8 @@ class AutomatedTestWidgetsFlutterBinding extends TestWidgetsFlutterBinding { // exception due to zone error boundaries. _pendingAsyncTasks!.complete(); _pendingAsyncTasks = null; - }); + } + return result; }); } diff --git a/packages/flutter_test/test/test_config/config_test_utils.dart b/packages/flutter_test/test/test_config/config_test_utils.dart index 6c1723933f..d86cf7b509 100644 --- a/packages/flutter_test/test/test_config/config_test_utils.dart +++ b/packages/flutter_test/test/test_config/config_test_utils.dart @@ -11,7 +11,7 @@ void testConfig( String? expectedStringValue, { Map otherExpectedValues = const {int: isNull}, }) { - final String actualStringValue = Zone.current[String] as String; + final String? actualStringValue = Zone.current[String] as String?; final Map otherActualValues = otherExpectedValues.map( (Type key, dynamic value) { return MapEntry(key, Zone.current[key]);