migrate rendering to nullsafety (#64621)
diff --git a/analysis_options.yaml b/analysis_options.yaml
index 9990dcb..a3adad6 100644
--- a/analysis_options.yaml
+++ b/analysis_options.yaml
@@ -202,6 +202,7 @@
- use_full_hex_values_for_flutter_colors
# - use_function_type_syntax_for_parameters # not yet tested
# - use_key_in_widget_constructors # not yet tested
+ - use_late_for_private_fields_and_variables
- use_rethrow_when_possible
# - use_setters_to_change_properties # not yet tested
# - use_string_buffers # has false positives: https://github.com/dart-lang/sdk/issues/34182
diff --git a/packages/flutter/analysis_options.yaml b/packages/flutter/analysis_options.yaml
index 0d25a67..00d1a5a 100644
--- a/packages/flutter/analysis_options.yaml
+++ b/packages/flutter/analysis_options.yaml
@@ -8,5 +8,6 @@
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 # https://github.com/dart-lang/language/issues/1018 , turned off until https://github.com/flutter/flutter/issues/61042
diff --git a/packages/flutter/lib/rendering.dart b/packages/flutter/lib/rendering.dart
index 51068bf..ea4c648 100644
--- a/packages/flutter/lib/rendering.dart
+++ b/packages/flutter/lib/rendering.dart
@@ -2,8 +2,6 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-// @dart = 2.8
-
/// The Flutter rendering tree.
///
/// To use, import `package:flutter/rendering.dart`.
diff --git a/packages/flutter/lib/src/animation/tween.dart b/packages/flutter/lib/src/animation/tween.dart
index 0d2137f..865423b 100644
--- a/packages/flutter/lib/src/animation/tween.dart
+++ b/packages/flutter/lib/src/animation/tween.dart
@@ -208,6 +208,20 @@
/// [Tween]s that use dedicated `lerp` methods instead of merely relying on the
/// operators (in particular, this allows them to handle null values in a more
/// useful manner).
+///
+/// ## Nullability
+///
+/// The [begin] and [end] fields are nullable; a [Tween] does not have to
+/// have non-null values specified when it is created.
+///
+/// If `T` is nullable, then [lerp] and [transform] may return null.
+/// This is typically seen in the case where [begin] is null and `t`
+/// is 0.0, or [end] is null and `t` is 1.0, or both are null (at any
+/// `t` value).
+///
+/// If `T` is not nullable, then [begin] and [end] must both be set to
+/// non-null values before using [lerp] or [transform], otherwise they
+/// will throw.
class Tween<T extends dynamic> extends Animatable<T> {
/// Creates a tween.
///
@@ -236,6 +250,9 @@
/// The default implementation of this method uses the [+], [-], and [*]
/// operators on `T`. The [begin] and [end] properties must therefore be
/// non-null by the time this method is called.
+ ///
+ /// In general, however, it is possible for this to return null, especially
+ /// when `t`=0.0 and [begin] is null, or `t`=1.0 and [end] is null.
@protected
T lerp(double t) {
assert(begin != null);
@@ -291,6 +308,9 @@
/// This class specializes the interpolation of [Tween<Color>] to use
/// [Color.lerp].
///
+/// The values can be null, representing no color (which is distinct to
+/// transparent black, as represented by [Colors.transparent]).
+///
/// See [Tween] for a discussion on how to use interpolation objects.
class ColorTween extends Tween<Color?> {
/// Creates a [Color] tween.
@@ -314,6 +334,8 @@
/// This class specializes the interpolation of [Tween<Size>] to use
/// [Size.lerp].
///
+/// The values can be null, representing [Size.zero].
+///
/// See [Tween] for a discussion on how to use interpolation objects.
class SizeTween extends Tween<Size?> {
/// Creates a [Size] tween.
@@ -332,6 +354,9 @@
/// This class specializes the interpolation of [Tween<Rect>] to use
/// [Rect.lerp].
///
+/// The values can be null, representing a zero-sized rectangle at the
+/// origin ([Rect.zero]).
+///
/// See [Tween] for a discussion on how to use interpolation objects.
class RectTween extends Tween<Rect?> {
/// Creates a [Rect] tween.
@@ -355,6 +380,9 @@
/// This is the closest approximation to a linear tween that is possible with an
/// integer. Compare to [StepTween] and [Tween<double>].
///
+/// The [begin] and [end] values must be set to non-null values before
+/// calling [lerp] or [transform].
+///
/// See [Tween] for a discussion on how to use interpolation objects.
class IntTween extends Tween<int> {
/// Creates an int tween.
@@ -380,6 +408,9 @@
/// This results in a value that is never greater than the equivalent
/// value from a linear double interpolation. Compare to [IntTween].
///
+/// The [begin] and [end] values must be set to non-null values before
+/// calling [lerp] or [transform].
+///
/// See [Tween] for a discussion on how to use interpolation objects.
class StepTween extends Tween<int> {
/// Creates an [int] tween that floors.
diff --git a/packages/flutter/lib/src/foundation/diagnostics.dart b/packages/flutter/lib/src/foundation/diagnostics.dart
index d75606a..03f7081 100644
--- a/packages/flutter/lib/src/foundation/diagnostics.dart
+++ b/packages/flutter/lib/src/foundation/diagnostics.dart
@@ -3377,13 +3377,10 @@
///
/// * [toString], for a brief description of the object.
/// * [toStringDeep], for a description of the subtree rooted at this object.
- String? toStringShallow({
+ String toStringShallow({
String joiner = ', ',
DiagnosticLevel minLevel = DiagnosticLevel.debug,
}) {
- if (kReleaseMode) {
- return toString();
- }
String? shallowString;
assert(() {
final StringBuffer result = StringBuffer();
@@ -3398,7 +3395,7 @@
shallowString = result.toString();
return true;
}());
- return shallowString;
+ return shallowString ?? toString();
}
/// Returns a string representation of this node and its descendants.
@@ -3470,13 +3467,10 @@
}
@override
- String? toStringShallow({
+ String toStringShallow({
String joiner = ', ',
DiagnosticLevel minLevel = DiagnosticLevel.debug,
}) {
- if (kReleaseMode) {
- return toString();
- }
String? shallowString;
assert(() {
final StringBuffer result = StringBuffer();
@@ -3491,7 +3485,7 @@
shallowString = result.toString();
return true;
}());
- return shallowString;
+ return shallowString ?? toString();
}
@override
diff --git a/packages/flutter/lib/src/gestures/binding.dart b/packages/flutter/lib/src/gestures/binding.dart
index d3ef4cc..912dc00 100644
--- a/packages/flutter/lib/src/gestures/binding.dart
+++ b/packages/flutter/lib/src/gestures/binding.dart
@@ -291,6 +291,7 @@
event is PointerHoverEvent ||
event is PointerAddedEvent ||
event is PointerRemovedEvent) {
+ assert(event.position != null);
dispatchEvent(event, hitTestResult);
}
}
diff --git a/packages/flutter/lib/src/gestures/converter.dart b/packages/flutter/lib/src/gestures/converter.dart
index 63c1d0d..5f4cead 100644
--- a/packages/flutter/lib/src/gestures/converter.dart
+++ b/packages/flutter/lib/src/gestures/converter.dart
@@ -48,6 +48,7 @@
static Iterable<PointerEvent> expand(Iterable<ui.PointerData> data, double devicePixelRatio) sync* {
for (final ui.PointerData datum in data) {
final Offset position = Offset(datum.physicalX, datum.physicalY) / devicePixelRatio;
+ assert(position != null);
final Offset delta = Offset(datum.physicalDeltaX, datum.physicalDeltaY) / devicePixelRatio;
final double radiusMinor = _toLogicalPixels(datum.radiusMinor, devicePixelRatio);
final double radiusMajor = _toLogicalPixels(datum.radiusMajor, devicePixelRatio);
diff --git a/packages/flutter/lib/src/painting/text_painter.dart b/packages/flutter/lib/src/painting/text_painter.dart
index 82713fb..935a9be 100644
--- a/packages/flutter/lib/src/painting/text_painter.dart
+++ b/packages/flutter/lib/src/painting/text_painter.dart
@@ -44,6 +44,9 @@
}) : assert(size != null),
assert(alignment != null);
+ /// A constant representing an empty placeholder.
+ static const PlaceholderDimensions empty = PlaceholderDimensions(size: Size.zero, alignment: ui.PlaceholderAlignment.bottom);
+
/// Width and height dimensions of the placeholder.
final Size size;
diff --git a/packages/flutter/lib/src/rendering/animated_size.dart b/packages/flutter/lib/src/rendering/animated_size.dart
index 689e6bf..65cd4af 100644
--- a/packages/flutter/lib/src/rendering/animated_size.dart
+++ b/packages/flutter/lib/src/rendering/animated_size.dart
@@ -2,8 +2,6 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-// @dart = 2.8
-
import 'package:flutter/animation.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/scheduler.dart';
@@ -76,13 +74,13 @@
/// The arguments [duration], [curve], [alignment], and [vsync] must
/// not be null.
RenderAnimatedSize({
- @required TickerProvider vsync,
- @required Duration duration,
- Duration reverseDuration,
+ required TickerProvider vsync,
+ required Duration duration,
+ Duration? reverseDuration,
Curve curve = Curves.linear,
AlignmentGeometry alignment = Alignment.center,
- TextDirection textDirection,
- RenderBox child,
+ TextDirection? textDirection,
+ RenderBox? child,
}) : assert(vsync != null),
assert(duration != null),
assert(curve != null),
@@ -102,11 +100,11 @@
);
}
- AnimationController _controller;
- CurvedAnimation _animation;
+ late final AnimationController _controller;
+ late final CurvedAnimation _animation;
final SizeTween _sizeTween = SizeTween();
- bool _hasVisualOverflow;
- double _lastValue;
+ late bool _hasVisualOverflow;
+ double? _lastValue;
/// The state this size animation is in.
///
@@ -116,7 +114,7 @@
RenderAnimatedSizeState _state = RenderAnimatedSizeState.start;
/// The duration of the animation.
- Duration get duration => _controller.duration;
+ Duration get duration => _controller.duration!;
set duration(Duration value) {
assert(value != null);
if (value == _controller.duration)
@@ -125,8 +123,8 @@
}
/// The duration of the animation when running in reverse.
- Duration get reverseDuration => _controller.reverseDuration;
- set reverseDuration(Duration value) {
+ Duration? get reverseDuration => _controller.reverseDuration;
+ set reverseDuration(Duration? value) {
if (value == _controller.reverseDuration)
return;
_controller.reverseDuration = value;
@@ -164,7 +162,7 @@
super.detach();
}
- Size get _animatedSize {
+ Size? get _animatedSize {
return _sizeTween.evaluate(_animation);
}
@@ -181,7 +179,7 @@
return;
}
- child.layout(constraints, parentUsesSize: true);
+ child!.layout(constraints, parentUsesSize: true);
assert(_state != null);
switch (_state) {
@@ -199,11 +197,11 @@
break;
}
- size = constraints.constrain(_animatedSize);
+ size = constraints.constrain(_animatedSize!);
alignChild();
- if (size.width < _sizeTween.end.width ||
- size.height < _sizeTween.end.height)
+ if (size.width < _sizeTween.end!.width ||
+ size.height < _sizeTween.end!.height)
_hasVisualOverflow = true;
}
@@ -217,7 +215,7 @@
/// We have the initial size to animate from, but we do not have the target
/// size to animate to, so we set both ends to child's size.
void _layoutStart() {
- _sizeTween.begin = _sizeTween.end = debugAdoptSize(child.size);
+ _sizeTween.begin = _sizeTween.end = debugAdoptSize(child!.size);
_state = RenderAnimatedSizeState.stable;
}
@@ -227,14 +225,14 @@
/// If during animation the size of the child changes we restart the
/// animation.
void _layoutStable() {
- if (_sizeTween.end != child.size) {
+ if (_sizeTween.end != child!.size) {
_sizeTween.begin = size;
- _sizeTween.end = debugAdoptSize(child.size);
+ _sizeTween.end = debugAdoptSize(child!.size);
_restartAnimation();
_state = RenderAnimatedSizeState.changed;
} else if (_controller.value == _controller.upperBound) {
// Animation finished. Reset target sizes.
- _sizeTween.begin = _sizeTween.end = debugAdoptSize(child.size);
+ _sizeTween.begin = _sizeTween.end = debugAdoptSize(child!.size);
} else if (!_controller.isAnimating) {
_controller.forward(); // resume the animation after being detached
}
@@ -247,9 +245,9 @@
/// changes again, we match the child's size, restart animation and go to
/// unstable state.
void _layoutChanged() {
- if (_sizeTween.end != child.size) {
+ if (_sizeTween.end != child!.size) {
// Child size changed again. Match the child's size and restart animation.
- _sizeTween.begin = _sizeTween.end = debugAdoptSize(child.size);
+ _sizeTween.begin = _sizeTween.end = debugAdoptSize(child!.size);
_restartAnimation();
_state = RenderAnimatedSizeState.unstable;
} else {
@@ -264,9 +262,9 @@
///
/// Continue tracking the child's size until is stabilizes.
void _layoutUnstable() {
- if (_sizeTween.end != child.size) {
+ if (_sizeTween.end != child!.size) {
// Still unstable. Continue tracking the child.
- _sizeTween.begin = _sizeTween.end = debugAdoptSize(child.size);
+ _sizeTween.begin = _sizeTween.end = debugAdoptSize(child!.size);
_restartAnimation();
} else {
// Child size stabilized.
diff --git a/packages/flutter/lib/src/rendering/binding.dart b/packages/flutter/lib/src/rendering/binding.dart
index c01e350..f3868ac 100644
--- a/packages/flutter/lib/src/rendering/binding.dart
+++ b/packages/flutter/lib/src/rendering/binding.dart
@@ -2,8 +2,6 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-// @dart = 2.8
-
import 'dart:async';
import 'dart:developer';
import 'dart:typed_data';
@@ -50,8 +48,8 @@
}
/// The current [RendererBinding], if one has been created.
- static RendererBinding get instance => _instance;
- static RendererBinding _instance;
+ static RendererBinding? get instance => _instance;
+ static RendererBinding? _instance;
@override
void initServiceExtensions() {
@@ -145,20 +143,25 @@
///
/// Called automatically when the binding is created.
void initRenderView() {
- assert(renderView == null);
+ assert(!_debugIsRenderViewInitialized);
+ assert(() {
+ _debugIsRenderViewInitialized = true;
+ return true;
+ }());
renderView = RenderView(configuration: createViewConfiguration(), window: window);
renderView.prepareInitialFrame();
}
+ bool _debugIsRenderViewInitialized = false;
/// The object that manages state about currently connected mice, for hover
/// notification.
- MouseTracker get mouseTracker => _mouseTracker;
- MouseTracker _mouseTracker;
+ MouseTracker get mouseTracker => _mouseTracker!;
+ MouseTracker? _mouseTracker;
/// The render tree's owner, which maintains dirty state for layout,
/// composite, paint, and accessibility semantics.
PipelineOwner get pipelineOwner => _pipelineOwner;
- PipelineOwner _pipelineOwner;
+ late PipelineOwner _pipelineOwner;
/// The render tree that's attached to the output surface.
RenderView get renderView => _pipelineOwner.rootNode as RenderView;
@@ -239,25 +242,26 @@
);
}
- SemanticsHandle _semanticsHandle;
+ SemanticsHandle? _semanticsHandle;
/// Creates a [MouseTracker] which manages state about currently connected
/// mice, for hover notification.
///
/// Used by testing framework to reinitialize the mouse tracker between tests.
@visibleForTesting
- void initMouseTracker([MouseTracker tracker]) {
+ void initMouseTracker([MouseTracker? tracker]) {
_mouseTracker?.dispose();
_mouseTracker = tracker ?? MouseTracker();
}
@override // from GestureBinding
- void dispatchEvent(PointerEvent event, HitTestResult hitTestResult) {
+ void dispatchEvent(PointerEvent event, HitTestResult? hitTestResult) {
if (hitTestResult != null ||
event is PointerHoverEvent ||
event is PointerAddedEvent ||
event is PointerRemovedEvent) {
- _mouseTracker.updateWithEvent(event,
+ assert(event.position != null);
+ _mouseTracker!.updateWithEvent(event,
() => hitTestResult ?? renderView.hitTestMouseTrackers(event.position));
}
super.dispatchEvent(event, hitTestResult);
@@ -278,7 +282,7 @@
}
}
- void _handleSemanticsAction(int id, SemanticsAction action, ByteData args) {
+ void _handleSemanticsAction(int id, SemanticsAction action, ByteData? args) {
_pipelineOwner.semanticsOwner?.performAction(
id,
action,
@@ -306,13 +310,13 @@
_debugMouseTrackerUpdateScheduled = true;
return true;
}());
- SchedulerBinding.instance.addPostFrameCallback((Duration duration) {
+ SchedulerBinding.instance!.addPostFrameCallback((Duration duration) {
assert(_debugMouseTrackerUpdateScheduled);
assert(() {
_debugMouseTrackerUpdateScheduled = false;
return true;
}());
- _mouseTracker.updateAllDevices(renderView.hitTestMouseTrackers);
+ _mouseTracker!.updateAllDevices(renderView.hitTestMouseTrackers);
});
}
@@ -455,29 +459,31 @@
@override
void hitTest(HitTestResult result, Offset position) {
assert(renderView != null);
+ assert(result != null);
+ assert(position != null);
renderView.hitTest(result, position: position);
super.hitTest(result, position);
}
Future<void> _forceRepaint() {
- RenderObjectVisitor visitor;
+ late RenderObjectVisitor visitor;
visitor = (RenderObject child) {
child.markNeedsPaint();
child.visitChildren(visitor);
};
- instance?.renderView?.visitChildren(visitor);
+ instance?.renderView.visitChildren(visitor);
return endOfFrame;
}
}
/// Prints a textual representation of the entire render tree.
void debugDumpRenderTree() {
- debugPrint(RendererBinding.instance?.renderView?.toStringDeep() ?? 'Render tree unavailable.');
+ debugPrint(RendererBinding.instance?.renderView.toStringDeep() ?? 'Render tree unavailable.');
}
/// Prints a textual representation of the entire layer tree.
void debugDumpLayerTree() {
- debugPrint(RendererBinding.instance?.renderView?.debugLayer?.toStringDeep() ?? 'Layer tree unavailable.');
+ debugPrint(RendererBinding.instance?.renderView.debugLayer?.toStringDeep() ?? 'Layer tree unavailable.');
}
/// Prints a textual representation of the entire semantics tree.
@@ -487,7 +493,7 @@
/// The order in which the children of a [SemanticsNode] will be printed is
/// controlled by the [childOrder] parameter.
void debugDumpSemanticsTree(DebugSemanticsDumpOrder childOrder) {
- debugPrint(RendererBinding.instance?.renderView?.debugSemantics?.toStringDeep(childOrder: childOrder) ?? 'Semantics not collected.');
+ debugPrint(RendererBinding.instance?.renderView.debugSemantics?.toStringDeep(childOrder: childOrder) ?? 'Semantics not collected.');
}
/// A concrete binding for applications that use the Rendering framework
@@ -502,7 +508,7 @@
///
/// The `root` render box is attached directly to the [renderView] and is
/// given constraints that require it to fill the window.
- RenderingFlutterBinding({ RenderBox root }) {
+ RenderingFlutterBinding({ RenderBox? root }) {
assert(renderView != null);
renderView.child = root;
}
diff --git a/packages/flutter/lib/src/rendering/box.dart b/packages/flutter/lib/src/rendering/box.dart
index 46d646e..38de16f 100644
--- a/packages/flutter/lib/src/rendering/box.dart
+++ b/packages/flutter/lib/src/rendering/box.dart
@@ -2,8 +2,6 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-// @dart = 2.8
-
import 'dart:math' as math;
import 'dart:ui' as ui show lerpDouble;
@@ -19,7 +17,7 @@
class _DebugSize extends Size {
_DebugSize(Size source, this._owner, this._canBeUsedByParent) : super.copy(source);
final RenderBox _owner;
- final bool/*!*/ _canBeUsedByParent;
+ final bool _canBeUsedByParent;
}
/// Immutable layout constraints for [RenderBox] layout.
@@ -112,8 +110,8 @@
/// being tight if the value is non-null, is tight if the value is not
/// infinite.
const BoxConstraints.tightFor({
- double width,
- double height,
+ double? width,
+ double? height,
}) : minWidth = width ?? 0.0,
maxWidth = width ?? double.infinity,
minHeight = height ?? 0.0,
@@ -146,8 +144,8 @@
/// If width or height is given, the constraints will require exactly the
/// given value in the given dimension.
const BoxConstraints.expand({
- double width,
- double height,
+ double? width,
+ double? height,
}) : minWidth = width ?? double.infinity,
maxWidth = width ?? double.infinity,
minHeight = height ?? double.infinity,
@@ -171,10 +169,10 @@
/// Creates a copy of this box constraints but with the given fields replaced with the new values.
BoxConstraints copyWith({
- double minWidth,
- double maxWidth,
- double minHeight,
- double maxHeight,
+ double? minWidth,
+ double? maxWidth,
+ double? minHeight,
+ double? maxHeight,
}) {
return BoxConstraints(
minWidth: minWidth ?? this.minWidth,
@@ -215,22 +213,22 @@
/// as close as possible to the original constraints.
BoxConstraints enforce(BoxConstraints constraints) {
return BoxConstraints(
- minWidth: minWidth.clamp(constraints.minWidth, constraints.maxWidth) as double,
- maxWidth: maxWidth.clamp(constraints.minWidth, constraints.maxWidth) as double,
- minHeight: minHeight.clamp(constraints.minHeight, constraints.maxHeight) as double,
- maxHeight: maxHeight.clamp(constraints.minHeight, constraints.maxHeight) as double,
+ minWidth: minWidth.clamp(constraints.minWidth, constraints.maxWidth),
+ maxWidth: maxWidth.clamp(constraints.minWidth, constraints.maxWidth),
+ minHeight: minHeight.clamp(constraints.minHeight, constraints.maxHeight),
+ maxHeight: maxHeight.clamp(constraints.minHeight, constraints.maxHeight),
);
}
/// Returns new box constraints with a tight width and/or height as close to
/// the given width and height as possible while still respecting the original
/// box constraints.
- BoxConstraints tighten({ double width, double height }) {
+ BoxConstraints tighten({ double? width, double? height }) {
return BoxConstraints(
- minWidth: width == null ? minWidth : width.clamp(minWidth, maxWidth) as double,
- maxWidth: width == null ? maxWidth : width.clamp(minWidth, maxWidth) as double,
- minHeight: height == null ? minHeight : height.clamp(minHeight, maxHeight) as double,
- maxHeight: height == null ? maxHeight : height.clamp(minHeight, maxHeight) as double,
+ minWidth: width == null ? minWidth : width.clamp(minWidth, maxWidth),
+ maxWidth: width == null ? maxWidth : width.clamp(minWidth, maxWidth),
+ minHeight: height == null ? minHeight : height.clamp(minHeight, maxHeight),
+ maxHeight: height == null ? maxHeight : height.clamp(minHeight, maxHeight),
);
}
@@ -256,14 +254,14 @@
/// possible to the given width.
double constrainWidth([ double width = double.infinity ]) {
assert(debugAssertIsValid());
- return width.clamp(minWidth, maxWidth) as double;
+ return width.clamp(minWidth, maxWidth);
}
/// Returns the height that both satisfies the constraints and is as close as
/// possible to the given height.
double constrainHeight([ double height = double.infinity ]) {
assert(debugAssertIsValid());
- return height.clamp(minHeight, maxHeight) as double;
+ return height.clamp(minHeight, maxHeight);
}
Size _debugPropagateDebugSize(Size size, Size result) {
@@ -468,12 +466,12 @@
/// object whose fields are all set to 0.0.
///
/// {@macro dart.ui.shadow.lerp}
- static BoxConstraints lerp(BoxConstraints/*?*/ a, BoxConstraints/*?*/ b, double t) {
+ static BoxConstraints? lerp(BoxConstraints? a, BoxConstraints? b, double t) {
assert(t != null);
if (a == null && b == null)
return null;
if (a == null)
- return b * t;
+ return b! * t;
if (b == null)
return a * (1.0 - t);
assert(a.debugAssertIsValid());
@@ -483,10 +481,10 @@
assert((a.minHeight.isFinite && b.minHeight.isFinite) || (a.minHeight == double.infinity && b.minHeight == double.infinity), 'Cannot interpolate between finite constraints and unbounded constraints.');
assert((a.maxHeight.isFinite && b.maxHeight.isFinite) || (a.maxHeight == double.infinity && b.maxHeight == double.infinity), 'Cannot interpolate between finite constraints and unbounded constraints.');
return BoxConstraints(
- minWidth: a.minWidth.isFinite ? ui.lerpDouble(a.minWidth, b.minWidth, t) : double.infinity,
- maxWidth: a.maxWidth.isFinite ? ui.lerpDouble(a.maxWidth, b.maxWidth, t) : double.infinity,
- minHeight: a.minHeight.isFinite ? ui.lerpDouble(a.minHeight, b.minHeight, t) : double.infinity,
- maxHeight: a.maxHeight.isFinite ? ui.lerpDouble(a.maxHeight, b.maxHeight, t) : double.infinity,
+ minWidth: a.minWidth.isFinite ? ui.lerpDouble(a.minWidth, b.minWidth, t)! : double.infinity,
+ maxWidth: a.maxWidth.isFinite ? ui.lerpDouble(a.maxWidth, b.maxWidth, t)! : double.infinity,
+ minHeight: a.minHeight.isFinite ? ui.lerpDouble(a.minHeight, b.minHeight, t)! : double.infinity,
+ maxHeight: a.maxHeight.isFinite ? ui.lerpDouble(a.maxHeight, b.maxHeight, t)! : double.infinity,
);
}
@@ -512,7 +510,7 @@
@override
bool debugAssertIsValid({
bool isAppliedConstraint = false,
- InformationCollector informationCollector,
+ InformationCollector? informationCollector,
}) {
assert(() {
void throwError(DiagnosticsNode message) {
@@ -636,6 +634,18 @@
/// [RenderBox]es.
typedef BoxHitTest = bool Function(BoxHitTestResult result, Offset position);
+/// Method signature for hit testing a [RenderBox] with a manually
+/// managed position (one that is passed out-of-band).
+///
+/// Used by [RenderSliverSingleBoxAdapter.hitTestBoxChild] to hit test
+/// [RenderBox] children of a [RenderSliver].
+///
+/// See also:
+///
+/// * [RenderBox.hitTest], which documents more details around hit testing
+/// [RenderBox]es.
+typedef BoxHitTestWithOutOfBandPosition = bool Function(BoxHitTestResult result);
+
/// The result of performing a hit test on [RenderBox]es.
///
/// An instance of this class is provided to [RenderBox.hitTest] to record the
@@ -725,10 +735,11 @@
/// * [addWithRawTransform], which takes a transform matrix that is directly
/// used to transform the position without any pre-processing.
bool addWithPaintTransform({
- @required Matrix4 transform,
- @required Offset position,
- @required BoxHitTest hitTest,
+ required Matrix4? transform,
+ required Offset position,
+ required BoxHitTest hitTest,
}) {
+ assert(position != null);
assert(hitTest != null);
if (transform != null) {
transform = Matrix4.tryInvert(PointerEvent.removePerspectiveTransform(transform));
@@ -763,14 +774,13 @@
/// * [addWithPaintTransform], which takes a generic paint transform matrix and
/// documents the intended usage of this API in more detail.
bool addWithPaintOffset({
- @required Offset offset,
- @required Offset position,
- @required BoxHitTest hitTest,
+ required Offset? offset,
+ required Offset position,
+ required BoxHitTest hitTest,
}) {
+ assert(position != null);
assert(hitTest != null);
- final Offset transformedPosition = position == null || offset == null
- ? position
- : position - offset;
+ final Offset transformedPosition = offset == null ? position : position - offset;
if (offset != null) {
pushOffset(-offset);
}
@@ -796,24 +806,20 @@
///
/// The function returns the return value of the `hitTest` callback.
///
- /// The `position` argument may be null, which will be forwarded to the
- /// `hitTest` callback as-is. Using null as the position can be useful if
- /// the child speaks a different hit test protocol then the parent and the
- /// position is not required to do the actual hit testing in that protocol.
- ///
/// See also:
///
/// * [addWithPaintTransform], which accomplishes the same thing, but takes a
/// _paint_ transform matrix.
bool addWithRawTransform({
- @required Matrix4 transform,
- @required Offset position,
- @required BoxHitTest hitTest,
+ required Matrix4? transform,
+ required Offset position,
+ required BoxHitTest hitTest,
}) {
+ assert(position != null);
assert(hitTest != null);
- final Offset transformedPosition = position == null || transform == null
- ? position
- : MatrixUtils.transformPoint(transform, position);
+ assert(position != null);
+ final Offset transformedPosition = transform == null ?
+ position : MatrixUtils.transformPoint(transform, position);
if (transform != null) {
pushTransform(transform);
}
@@ -823,6 +829,60 @@
}
return isHit;
}
+
+ /// Pass-through method for adding a hit test while manually managing
+ /// the position transformation logic.
+ ///
+ /// The actual hit testing of the child needs to be implemented in the
+ /// provided `hitTest` callback. The position needs to be handled by
+ /// the caller.
+ ///
+ /// The function returns the return value of the `hitTest` callback.
+ ///
+ /// A `paintOffset`, `paintTransform`, or `rawTransform` should be
+ /// passed to the method to update the hit test stack.
+ ///
+ /// * `paintOffset` has the semantics of the `offset` passed to
+ /// [addWithPaintOffset].
+ ///
+ /// * `paintTransform` has the semantics of the `transform` passed to
+ /// [addWithPaintTransform], except that it must be invertible; it
+ /// is the responsibility of the caller to ensure this.
+ ///
+ /// * `rawTransform` has the semantics of the `transform` passed to
+ /// [addWithRawTransform].
+ ///
+ /// Exactly one of these must be non-null.
+ ///
+ /// See also:
+ ///
+ /// * [addWithPaintTransform], which takes a generic paint transform matrix and
+ /// documents the intended usage of this API in more detail.
+ bool addWithOutOfBandPosition({
+ Offset? paintOffset,
+ Matrix4? paintTransform,
+ Matrix4? rawTransform,
+ required BoxHitTestWithOutOfBandPosition hitTest,
+ }) {
+ assert(hitTest != null);
+ assert((paintOffset == null && paintTransform == null && rawTransform != null) ||
+ (paintOffset == null && paintTransform != null && rawTransform == null) ||
+ (paintOffset != null && paintTransform == null && rawTransform == null),
+ 'Exactly one transform or offset argument must be provided.');
+ if (paintOffset != null) {
+ pushOffset(-paintOffset);
+ } else if (rawTransform != null) {
+ pushTransform(rawTransform);
+ } else {
+ assert(paintTransform != null);
+ paintTransform = Matrix4.tryInvert(PointerEvent.removePerspectiveTransform(paintTransform!));
+ assert(paintTransform != null, 'paintTransform must be invertible.');
+ pushTransform(paintTransform!);
+ }
+ final bool isHit = hitTest(this);
+ popTransform();
+ return isHit;
+ }
}
/// A hit test entry used by [RenderBox].
@@ -1294,9 +1354,9 @@
child.parentData = BoxParentData();
}
- Map<_IntrinsicDimensionsCacheEntry, double/*!*/> _cachedIntrinsicDimensions;
+ Map<_IntrinsicDimensionsCacheEntry, double>? _cachedIntrinsicDimensions;
- double/*!*/ _computeIntrinsicDimension(_IntrinsicDimension dimension, double argument, double/*!*/ computer(double argument)) {
+ double _computeIntrinsicDimension(_IntrinsicDimension dimension, double argument, double computer(double argument)) {
assert(RenderObject.debugCheckingIntrinsics || !debugDoingThisResize); // performResize should not depend on anything except the incoming constraints
bool shouldCache = true;
assert(() {
@@ -1308,7 +1368,7 @@
}());
if (shouldCache) {
_cachedIntrinsicDimensions ??= <_IntrinsicDimensionsCacheEntry, double>{};
- return _cachedIntrinsicDimensions.putIfAbsent(
+ return _cachedIntrinsicDimensions!.putIfAbsent(
_IntrinsicDimensionsCacheEntry(dimension, argument),
() => computer(argument),
);
@@ -1332,9 +1392,12 @@
///
/// Do not override this method. Instead, implement [computeMinIntrinsicWidth].
@mustCallSuper
- double getMinIntrinsicWidth(double/*!*/ height) {
+ double getMinIntrinsicWidth(double height) {
assert(() {
- if (height == null) {
+ // `height` has a non-nullable return type, but might be null when
+ // running with weak checking, so we need to null check it anyway (and
+ // ignore the warning that the null-handling logic is dead code).
+ if (height == null) { // ignore: dead_code
throw FlutterError.fromParts(<DiagnosticsNode>[
ErrorSummary('The height argument to getMinIntrinsicWidth was null.'),
ErrorDescription('The argument to getMinIntrinsicWidth must not be negative or null.'),
@@ -1455,7 +1518,7 @@
/// * [computeMaxIntrinsicWidth], which computes the smallest width beyond
/// which increasing the width never decreases the preferred height.
@protected
- double/*!*/ computeMinIntrinsicWidth(double/*!*/ height) {
+ double computeMinIntrinsicWidth(double height) {
return 0.0;
}
@@ -1477,9 +1540,12 @@
/// Do not override this method. Instead, implement
/// [computeMaxIntrinsicWidth].
@mustCallSuper
- double getMaxIntrinsicWidth(double/*!*/ height) {
+ double getMaxIntrinsicWidth(double height) {
assert(() {
- if (height == null) {
+ // `height` has a non-nullable return type, but might be null when
+ // running with weak checking, so we need to null check it anyway (and
+ // ignore the warning that the null-handling logic is dead code).
+ if (height == null) { // ignore: dead_code
throw FlutterError.fromParts(<DiagnosticsNode>[
ErrorSummary('The height argument to getMaxIntrinsicWidth was null.'),
ErrorDescription('The argument to getMaxIntrinsicWidth must not be negative or null.'),
@@ -1535,7 +1601,7 @@
///
/// * [computeMinIntrinsicWidth], which has usage examples.
@protected
- double/*!*/ computeMaxIntrinsicWidth(double/*!*/ height) {
+ double computeMaxIntrinsicWidth(double height) {
return 0.0;
}
@@ -1556,9 +1622,12 @@
/// Do not override this method. Instead, implement
/// [computeMinIntrinsicHeight].
@mustCallSuper
- double getMinIntrinsicHeight(double/*!*/ width) {
+ double getMinIntrinsicHeight(double width) {
assert(() {
- if (width == null) {
+ // `width` has a non-nullable return type, but might be null when
+ // running with weak checking, so we need to null check it anyway (and
+ // ignore the warning that the null-handling logic is dead code).
+ if (width == null) { // ignore: dead_code
throw FlutterError.fromParts(<DiagnosticsNode>[
ErrorSummary('The width argument to getMinIntrinsicHeight was null.'),
ErrorDescription('The argument to getMinIntrinsicHeight must not be negative or null.'),
@@ -1612,7 +1681,7 @@
/// * [computeMaxIntrinsicHeight], which computes the smallest height beyond
/// which increasing the height never decreases the preferred width.
@protected
- double/*!*/ computeMinIntrinsicHeight(double/*!*/ width) {
+ double computeMinIntrinsicHeight(double width) {
return 0.0;
}
@@ -1634,9 +1703,12 @@
/// Do not override this method. Instead, implement
/// [computeMaxIntrinsicHeight].
@mustCallSuper
- double getMaxIntrinsicHeight(double/*!*/ width) {
+ double getMaxIntrinsicHeight(double width) {
assert(() {
- if (width == null) {
+ // `width` has a non-nullable return type, but might be null when
+ // running with weak checking, so we need to null check it anyway (and
+ // ignore the warning that the null-handling logic is dead code).
+ if (width == null) { // ignore: dead_code
throw FlutterError.fromParts(<DiagnosticsNode>[
ErrorSummary('The width argument to getMaxIntrinsicHeight was null.'),
ErrorDescription('The argument to getMaxIntrinsicHeight must not be negative or null.'),
@@ -1692,7 +1764,7 @@
///
/// * [computeMinIntrinsicWidth], which has usage examples.
@protected
- double/*!*/ computeMaxIntrinsicHeight(double/*!*/ width) {
+ double computeMaxIntrinsicHeight(double width) {
return 0.0;
}
@@ -1709,10 +1781,10 @@
/// [performResize] functions. If you wish to change the size of a box outside
/// of those functions, call [markNeedsLayout] instead to schedule a layout of
/// the box.
- Size/*!*/ get size {
+ Size get size {
assert(hasSize, 'RenderBox was not laid out: ${toString()}');
assert(() {
- final Size _size = this._size;
+ final Size? _size = this._size;
if (_size is _DebugSize) {
assert(_size._owner == this);
if (RenderObject.debugActiveLayout != null) {
@@ -1731,14 +1803,14 @@
}
return true;
}());
- return _size;
+ return _size!;
}
- /*late*/ Size/*!*/ _size;
+ Size? _size;
/// Setting the size, in checked mode, triggers some analysis of the render box,
/// as implemented by [debugAssertDoesMeetConstraints], including calling the intrinsic
/// sizing methods and checking that they meet certain invariants.
@protected
- set size(Size/*!*/ value) {
+ set size(Size value) {
assert(!(debugDoingThisResize && debugDoingThisLayout));
assert(sizedByParent || !debugDoingThisResize);
assert(() {
@@ -1756,7 +1828,7 @@
information.add(ErrorDescription(
'The size setter was called from outside layout (neither performResize() nor performLayout() were being run for this object).'
));
- if (owner != null && owner.debugDoingLayout)
+ if (owner != null && owner!.debugDoingLayout)
information.add(ErrorDescription('Only the object itself can set its size. It is a contract violation for other objects to set it.'));
}
if (sizedByParent)
@@ -1852,7 +1924,7 @@
size = size;
}
- Map<TextBaseline/*!*/, double> _cachedBaselines;
+ Map<TextBaseline, double?>? _cachedBaselines;
static bool _debugDoingBaseline = false;
static bool _debugSetDoingBaseline(bool value) {
_debugDoingBaseline = value;
@@ -1875,21 +1947,21 @@
///
/// When implementing a [RenderBox] subclass, to override the baseline
/// computation, override [computeDistanceToActualBaseline].
- double getDistanceToBaseline(TextBaseline/*!*/ baseline, { bool onlyReal = false }) {
+ double? getDistanceToBaseline(TextBaseline baseline, { bool onlyReal = false }) {
assert(!_debugDoingBaseline, 'Please see the documentation for computeDistanceToActualBaseline for the required calling conventions of this method.');
assert(!debugNeedsLayout);
assert(() {
- final RenderObject parent = this.parent as RenderObject;
- if (owner.debugDoingLayout)
- return (RenderObject.debugActiveLayout == parent) && parent.debugDoingThisLayout;
- if (owner.debugDoingPaint)
- return ((RenderObject.debugActivePaint == parent) && parent.debugDoingThisPaint) ||
+ final RenderObject? parent = this.parent as RenderObject?;
+ if (owner!.debugDoingLayout)
+ return (RenderObject.debugActiveLayout == parent) && parent!.debugDoingThisLayout;
+ if (owner!.debugDoingPaint)
+ return ((RenderObject.debugActivePaint == parent) && parent!.debugDoingThisPaint) ||
((RenderObject.debugActivePaint == this) && debugDoingThisPaint);
assert(parent == this.parent);
return false;
}());
assert(_debugSetDoingBaseline(true));
- final double result = getDistanceToActualBaseline(baseline);
+ final double? result = getDistanceToActualBaseline(baseline);
assert(_debugSetDoingBaseline(false));
if (result == null && !onlyReal)
return size.height;
@@ -1903,11 +1975,11 @@
/// outside those two methods.
@protected
@mustCallSuper
- double getDistanceToActualBaseline(TextBaseline/*!*/ baseline) {
+ double? getDistanceToActualBaseline(TextBaseline baseline) {
assert(_debugDoingBaseline, 'Please see the documentation for computeDistanceToActualBaseline for the required calling conventions of this method.');
- _cachedBaselines ??= <TextBaseline, double>{};
- _cachedBaselines.putIfAbsent(baseline, () => computeDistanceToActualBaseline(baseline));
- return _cachedBaselines[baseline];
+ _cachedBaselines ??= <TextBaseline, double?>{};
+ _cachedBaselines!.putIfAbsent(baseline, () => computeDistanceToActualBaseline(baseline));
+ return _cachedBaselines![baseline];
}
/// Returns the distance from the y-coordinate of the position of the box to
@@ -1935,7 +2007,7 @@
/// [computeDistanceToActualBaseline], the internal implementation, and not
/// [getDistanceToBaseline], the public entry point for this API).
@protected
- double computeDistanceToActualBaseline(TextBaseline baseline) {
+ double? computeDistanceToActualBaseline(TextBaseline baseline) {
assert(_debugDoingBaseline, 'Please see the documentation for computeDistanceToActualBaseline for the required calling conventions of this method.');
return null;
}
@@ -1962,7 +2034,7 @@
]);
}
// verify that the size is not infinite
- if (!_size.isFinite) {
+ if (!_size!.isFinite) {
final List<DiagnosticsNode> information = <DiagnosticsNode>[
ErrorSummary('$runtimeType object was given an infinite size during layout.'),
ErrorDescription(
@@ -1993,7 +2065,7 @@
]);
}
// verify that the size is within the constraints
- if (!constraints.isSatisfiedBy(_size)) {
+ if (!constraints.isSatisfiedBy(_size!)) {
throw FlutterError.fromParts(<DiagnosticsNode>[
ErrorSummary('$runtimeType does not meet its constraints.'),
DiagnosticsProperty<BoxConstraints>('Constraints', constraints, style: DiagnosticsTreeStyle.errorProperty),
@@ -2058,8 +2130,8 @@
@override
void markNeedsLayout() {
- if ((_cachedBaselines != null && _cachedBaselines.isNotEmpty) ||
- (_cachedIntrinsicDimensions != null && _cachedIntrinsicDimensions.isNotEmpty)) {
+ if ((_cachedBaselines != null && _cachedBaselines!.isNotEmpty) ||
+ (_cachedIntrinsicDimensions != null && _cachedIntrinsicDimensions!.isNotEmpty)) {
// If we have cached data, then someone must have used our data.
// Since the parent will shortly be marked dirty, we can forget that they
// used the baseline and/or intrinsic dimensions. If they use them again,
@@ -2123,7 +2195,7 @@
/// called. For example, a render object might be a child of a [RenderOpacity]
/// object, which calls [hitTest] on its children when its opacity is zero
/// even through it does not [paint] its children.
- bool hitTest(BoxHitTestResult result, { @required Offset position }) {
+ bool hitTest(BoxHitTestResult result, { required Offset position }) {
assert(() {
if (!hasSize) {
if (debugNeedsLayout) {
@@ -2159,7 +2231,7 @@
}
return true;
}());
- if (_size.contains(position)) {
+ if (_size!.contains(position)) {
if (hitTestChildren(result, position: position) || hitTestSelf(position)) {
result.add(BoxHitTestEntry(this, position));
return true;
@@ -2208,7 +2280,7 @@
/// Used by [hitTest]. If you override [hitTest] and do not call this
/// function, then you don't need to implement this function.
@protected
- bool hitTestChildren(BoxHitTestResult result, { Offset position }) => false;
+ bool hitTestChildren(BoxHitTestResult result, { required Offset position }) => false;
/// Multiply the transform from the parent's coordinate system to this box's
/// coordinate system into the given transform.
@@ -2261,7 +2333,7 @@
/// object) instead of from the global coordinate system.
///
/// This method is implemented in terms of [getTransformTo].
- Offset globalToLocal(Offset point, { RenderObject ancestor }) {
+ Offset globalToLocal(Offset point, { RenderObject? ancestor }) {
// We want to find point (p) that corresponds to a given point on the
// screen (s), but that also physically resides on the local render plane,
// so that it is useful for visually accurate gesture processing in the
@@ -2296,7 +2368,7 @@
/// This method is implemented in terms of [getTransformTo]. If the transform
/// matrix puts the given `point` on the line at infinity (for instance, when
/// the transform matrix is the zero matrix), this method returns (NaN, NaN).
- Offset localToGlobal(Offset point, { RenderObject ancestor }) {
+ Offset localToGlobal(Offset point, { RenderObject? ancestor }) {
return MatrixUtils.transformPoint(getTransformTo(ancestor), point);
}
@@ -2408,7 +2480,7 @@
..strokeWidth = 0.25;
Path path;
// ideographic baseline
- final double baselineI = getDistanceToBaseline(TextBaseline.ideographic, onlyReal: true);
+ final double? baselineI = getDistanceToBaseline(TextBaseline.ideographic, onlyReal: true);
if (baselineI != null) {
paint.color = const Color(0xFFFFD000);
path = Path();
@@ -2417,7 +2489,7 @@
context.canvas.drawPath(path, paint);
}
// alphabetic baseline
- final double baselineA = getDistanceToBaseline(TextBaseline.alphabetic, onlyReal: true);
+ final double? baselineA = getDistanceToBaseline(TextBaseline.alphabetic, onlyReal: true);
if (baselineA != null) {
paint.color = const Color(0xFF00FF00);
path = Path();
@@ -2466,15 +2538,15 @@
///
/// Useful when the children are displayed vertically in the same order they
/// appear in the child list.
- double defaultComputeDistanceToFirstActualBaseline(TextBaseline baseline) {
+ double? defaultComputeDistanceToFirstActualBaseline(TextBaseline baseline) {
assert(!debugNeedsLayout);
- ChildType child = firstChild;
+ ChildType? child = firstChild;
while (child != null) {
- final ParentDataType childParentData = child.parentData as ParentDataType;
- final double result = child.getDistanceToActualBaseline(baseline);
+ final ParentDataType? childParentData = child.parentData as ParentDataType?;
+ final double? result = child.getDistanceToActualBaseline(baseline);
if (result != null)
- return result + childParentData.offset.dy;
- child = childParentData.nextSibling;
+ return result + childParentData!.offset.dy;
+ child = childParentData!.nextSibling;
}
return null;
}
@@ -2483,13 +2555,13 @@
///
/// Useful when the vertical position of the children isn't determined by the
/// order in the child list.
- double defaultComputeDistanceToHighestActualBaseline(TextBaseline baseline) {
+ double? defaultComputeDistanceToHighestActualBaseline(TextBaseline baseline) {
assert(!debugNeedsLayout);
- double result;
- ChildType child = firstChild;
+ double? result;
+ ChildType? child = firstChild;
while (child != null) {
final ParentDataType childParentData = child.parentData as ParentDataType;
- double candidate = child.getDistanceToActualBaseline(baseline);
+ double? candidate = child.getDistanceToActualBaseline(baseline);
if (candidate != null) {
candidate += childParentData.offset.dy;
if (result != null)
@@ -2511,17 +2583,17 @@
///
/// * [defaultPaint], which paints the children appropriate for this
/// hit-testing strategy.
- bool defaultHitTestChildren(BoxHitTestResult result, { Offset position }) {
+ bool defaultHitTestChildren(BoxHitTestResult result, { required Offset position }) {
// The x, y parameters have the top left of the node's box as the origin.
- ChildType child = lastChild;
+ ChildType? child = lastChild;
while (child != null) {
final ParentDataType childParentData = child.parentData as ParentDataType;
final bool isHit = result.addWithPaintOffset(
offset: childParentData.offset,
position: position,
- hitTest: (BoxHitTestResult result, Offset transformed) {
+ hitTest: (BoxHitTestResult result, Offset? transformed) {
assert(transformed == position - childParentData.offset);
- return child.hitTest(result, position: transformed);
+ return child!.hitTest(result, position: transformed!);
},
);
if (isHit)
@@ -2538,7 +2610,7 @@
/// * [defaultHitTestChildren], which implements hit-testing of the children
/// in a manner appropriate for this painting strategy.
void defaultPaint(PaintingContext context, Offset offset) {
- ChildType child = firstChild;
+ ChildType? child = firstChild;
while (child != null) {
final ParentDataType childParentData = child.parentData as ParentDataType;
context.paintChild(child, childParentData.offset + offset);
@@ -2553,7 +2625,7 @@
/// walking the child list directly.
List<ChildType> getChildrenAsList() {
final List<ChildType> result = <ChildType>[];
- RenderBox child = firstChild;
+ RenderBox? child = firstChild;
while (child != null) {
final ParentDataType childParentData = child.parentData as ParentDataType;
result.add(child as ChildType);
diff --git a/packages/flutter/lib/src/rendering/custom_layout.dart b/packages/flutter/lib/src/rendering/custom_layout.dart
index 22ff89c..485568b 100644
--- a/packages/flutter/lib/src/rendering/custom_layout.dart
+++ b/packages/flutter/lib/src/rendering/custom_layout.dart
@@ -2,8 +2,6 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-// @dart = 2.8
-
import 'package:flutter/foundation.dart';
import 'box.dart';
@@ -14,7 +12,7 @@
/// [ParentData] used by [RenderCustomMultiChildLayoutBox].
class MultiChildLayoutParentData extends ContainerBoxParentData<RenderBox> {
/// An object representing the identity of this child.
- Object id;
+ Object? id;
@override
String toString() => '${super.toString()}; id=$id';
@@ -120,20 +118,19 @@
/// Creates a layout delegate.
///
/// The layout will update whenever [relayout] notifies its listeners.
- MultiChildLayoutDelegate({ Listenable relayout }) : _relayout = relayout;
+ MultiChildLayoutDelegate({ Listenable? relayout }) : _relayout = relayout;
- final Listenable _relayout;
+ final Listenable? _relayout;
- // TODO(ianh): make these late final
- /*late*/ Map<Object/*!*/, RenderBox>/*!*/ _idToChild;
- /*late*/ Set<RenderBox/*!*/>/*!*/ _debugChildrenNeedingLayout;
+ Map<Object, RenderBox>? _idToChild;
+ Set<RenderBox>? _debugChildrenNeedingLayout;
/// True if a non-null LayoutChild was provided for the specified id.
///
/// Call this from the [performLayout] or [getSize] methods to
/// determine which children are available, if the child list might
/// vary.
- bool hasChild(Object childId) => _idToChild[childId] != null;
+ bool hasChild(Object childId) => _idToChild![childId] != null;
/// Ask the child to update its layout within the limits specified by
/// the constraints parameter. The child's size is returned.
@@ -141,8 +138,8 @@
/// Call this from your [performLayout] function to lay out each
/// child. Every child must be laid out using this function exactly
/// once each time the [performLayout] function is called.
- Size/*!*/ layoutChild(Object childId, BoxConstraints constraints) {
- final RenderBox child = _idToChild[childId];
+ Size layoutChild(Object childId, BoxConstraints constraints) {
+ final RenderBox? child = _idToChild![childId];
assert(() {
if (child == null) {
throw FlutterError(
@@ -150,7 +147,7 @@
'There is no child with the id "$childId".'
);
}
- if (!_debugChildrenNeedingLayout.remove(child)) {
+ if (!_debugChildrenNeedingLayout!.remove(child)) {
throw FlutterError(
'The $this custom multichild layout delegate tried to lay out the child with id "$childId" more than once.\n'
'Each child must be laid out exactly once.'
@@ -171,7 +168,7 @@
}
return true;
}());
- child.layout(constraints, parentUsesSize: true);
+ child!.layout(constraints, parentUsesSize: true);
return child.size;
}
@@ -182,7 +179,7 @@
/// remain unchanged. Children initially have their position set to
/// (0,0), i.e. the top left of the [RenderCustomMultiChildLayoutBox].
void positionChild(Object childId, Offset offset) {
- final RenderBox child = _idToChild[childId];
+ final RenderBox? child = _idToChild![childId];
assert(() {
if (child == null) {
throw FlutterError(
@@ -190,14 +187,17 @@
'There is no child with the id "$childId".'
);
}
- if (offset == null) {
+ // `offset` has a non-nullable return type, but might be null when
+ // running with weak checking, so we need to null check it anyway (and
+ // ignore the warning that the null-handling logic is dead code).
+ if (offset == null) { // ignore: dead_code
throw FlutterError(
'The $this custom multichild layout delegate provided a null position for the child with id "$childId".'
);
}
return true;
}());
- final MultiChildLayoutParentData childParentData = child.parentData as MultiChildLayoutParentData;
+ final MultiChildLayoutParentData childParentData = child!.parentData as MultiChildLayoutParentData;
childParentData.offset = offset;
}
@@ -206,14 +206,13 @@
return DiagnosticsProperty<RenderBox>('${childParentData.id}', child);
}
- void _callPerformLayout(Size size, RenderBox firstChild) {
+ void _callPerformLayout(Size size, RenderBox? firstChild) {
// A particular layout delegate could be called reentrantly, e.g. if it used
// by both a parent and a child. So, we must restore the _idToChild map when
// we return.
- final Map<Object, RenderBox> previousIdToChild = _idToChild;
+ final Map<Object, RenderBox>? previousIdToChild = _idToChild;
- // TODO(ianh): make the next line final
- /*late*/ Set<RenderBox>/*!*/ debugPreviousChildrenNeedingLayout;
+ Set<RenderBox>? debugPreviousChildrenNeedingLayout;
assert(() {
debugPreviousChildrenNeedingLayout = _debugChildrenNeedingLayout;
_debugChildrenNeedingLayout = <RenderBox>{};
@@ -222,36 +221,36 @@
try {
_idToChild = <Object, RenderBox>{};
- RenderBox child = firstChild;
+ RenderBox? child = firstChild;
while (child != null) {
final MultiChildLayoutParentData childParentData = child.parentData as MultiChildLayoutParentData;
assert(() {
if (childParentData.id == null) {
throw FlutterError.fromParts(<DiagnosticsNode>[
ErrorSummary('Every child of a RenderCustomMultiChildLayoutBox must have an ID in its parent data.'),
- child.describeForError('The following child has no ID'),
+ child!.describeForError('The following child has no ID'),
]);
}
return true;
}());
- _idToChild[childParentData.id] = child;
+ _idToChild![childParentData.id!] = child;
assert(() {
- _debugChildrenNeedingLayout.add(child);
+ _debugChildrenNeedingLayout!.add(child!);
return true;
}());
child = childParentData.nextSibling;
}
performLayout(size);
assert(() {
- if (_debugChildrenNeedingLayout.isNotEmpty) {
+ if (_debugChildrenNeedingLayout!.isNotEmpty) {
throw FlutterError.fromParts(<DiagnosticsNode>[
ErrorSummary('Each child must be laid out exactly once.'),
DiagnosticsBlock(
name:
'The $this custom multichild layout delegate forgot '
'to lay out the following '
- '${_debugChildrenNeedingLayout.length > 1 ? 'children' : 'child'}',
- properties: _debugChildrenNeedingLayout.map<DiagnosticsNode>(_debugDescribeChild).toList(),
+ '${_debugChildrenNeedingLayout!.length > 1 ? 'children' : 'child'}',
+ properties: _debugChildrenNeedingLayout!.map<DiagnosticsNode>(_debugDescribeChild).toList(),
style: DiagnosticsTreeStyle.whitespace,
),
]);
@@ -314,8 +313,8 @@
///
/// The [delegate] argument must not be null.
RenderCustomMultiChildLayoutBox({
- List<RenderBox> children,
- @required MultiChildLayoutDelegate delegate,
+ List<RenderBox>? children,
+ required MultiChildLayoutDelegate delegate,
}) : assert(delegate != null),
_delegate = delegate {
addAll(children);
@@ -339,20 +338,20 @@
markNeedsLayout();
_delegate = newDelegate;
if (attached) {
- oldDelegate?._relayout?.removeListener(markNeedsLayout);
- newDelegate?._relayout?.addListener(markNeedsLayout);
+ oldDelegate._relayout?.removeListener(markNeedsLayout);
+ newDelegate._relayout?.addListener(markNeedsLayout);
}
}
@override
void attach(PipelineOwner owner) {
super.attach(owner);
- _delegate?._relayout?.addListener(markNeedsLayout);
+ _delegate._relayout?.addListener(markNeedsLayout);
}
@override
void detach() {
- _delegate?._relayout?.removeListener(markNeedsLayout);
+ _delegate._relayout?.removeListener(markNeedsLayout);
super.detach();
}
@@ -409,7 +408,7 @@
}
@override
- bool hitTestChildren(BoxHitTestResult result, { Offset position }) {
+ bool hitTestChildren(BoxHitTestResult result, { required Offset position }) {
return defaultHitTestChildren(result, position: position);
}
}
diff --git a/packages/flutter/lib/src/rendering/custom_paint.dart b/packages/flutter/lib/src/rendering/custom_paint.dart
index 241fe4f..bb8cac9 100644
--- a/packages/flutter/lib/src/rendering/custom_paint.dart
+++ b/packages/flutter/lib/src/rendering/custom_paint.dart
@@ -2,8 +2,6 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-// @dart = 2.8
-
import 'dart:collection';
import 'package:flutter/foundation.dart';
@@ -134,9 +132,9 @@
/// Creates a custom painter.
///
/// The painter will repaint whenever `repaint` notifies its listeners.
- const CustomPainter({ Listenable repaint }) : _repaint = repaint;
+ const CustomPainter({ Listenable? repaint }) : _repaint = repaint;
- final Listenable _repaint;
+ final Listenable? _repaint;
/// Register a closure to be notified when it is time to repaint.
///
@@ -203,7 +201,7 @@
/// * [SemanticsConfiguration.isSemanticBoundary], which causes new
/// [SemanticsNode]s to be added to the semantics tree.
/// * [RenderCustomPaint], which uses this getter to build semantics.
- SemanticsBuilderCallback get semanticsBuilder => null;
+ SemanticsBuilderCallback? get semanticsBuilder => null;
/// Called whenever a new instance of the custom painter delegate class is
/// provided to the [RenderCustomPaint] object, or any time that a new
@@ -267,7 +265,7 @@
/// image that should be considered a "hit", false if it corresponds to a
/// point that should be considered outside the painted image, and null to use
/// the default behavior.
- bool hitTest(Offset position) => null;
+ bool? hitTest(Offset position) => null;
@override
String toString() => '${describeIdentity(this)}(${ _repaint?.toString() ?? "" })';
@@ -295,8 +293,8 @@
/// Arguments `rect` and `properties` must not be null.
const CustomPainterSemantics({
this.key,
- @required this.rect,
- @required this.properties,
+ required this.rect,
+ required this.properties,
this.transform,
this.tags,
}) : assert(rect != null),
@@ -312,7 +310,7 @@
/// [SemanticsNode] will be updated using this instance.
///
/// This value is assigned to [SemanticsNode.key] during update.
- final Key key;
+ final Key? key;
/// The location and size of the box on the canvas where this piece of semantic
/// information applies.
@@ -324,7 +322,7 @@
/// coordinate system.
///
/// This value is assigned to [SemanticsNode.transform] during update.
- final Matrix4 transform;
+ final Matrix4? transform;
/// Contains properties that are assigned to the [SemanticsNode] created or
/// updated from this object.
@@ -339,7 +337,7 @@
/// semantics tree.
///
/// This value is assigned to [SemanticsNode.tags] during update.
- final Set<SemanticsTag> tags;
+ final Set<SemanticsTag>? tags;
}
/// Provides a canvas on which to draw during the paint phase.
@@ -370,12 +368,12 @@
class RenderCustomPaint extends RenderProxyBox {
/// Creates a render object that delegates its painting.
RenderCustomPaint({
- CustomPainter painter,
- CustomPainter foregroundPainter,
+ CustomPainter? painter,
+ CustomPainter? foregroundPainter,
Size preferredSize = Size.zero,
this.isComplex = false,
this.willChange = false,
- RenderBox child,
+ RenderBox? child,
}) : assert(preferredSize != null),
_painter = painter,
_foregroundPainter = foregroundPainter,
@@ -385,8 +383,8 @@
/// The background custom paint delegate.
///
/// This painter, if non-null, is called to paint behind the children.
- CustomPainter get painter => _painter;
- CustomPainter _painter;
+ CustomPainter? get painter => _painter;
+ CustomPainter? _painter;
/// Set a new background custom paint delegate.
///
/// If the new delegate is the same as the previous one, this does nothing.
@@ -399,10 +397,10 @@
/// delegate will be called.
///
/// If the new value is null, then there is no background custom painter.
- set painter(CustomPainter value) {
+ set painter(CustomPainter? value) {
if (_painter == value)
return;
- final CustomPainter oldPainter = _painter;
+ final CustomPainter? oldPainter = _painter;
_painter = value;
_didUpdatePainter(_painter, oldPainter);
}
@@ -410,8 +408,8 @@
/// The foreground custom paint delegate.
///
/// This painter, if non-null, is called to paint in front of the children.
- CustomPainter get foregroundPainter => _foregroundPainter;
- CustomPainter _foregroundPainter;
+ CustomPainter? get foregroundPainter => _foregroundPainter;
+ CustomPainter? _foregroundPainter;
/// Set a new foreground custom paint delegate.
///
/// If the new delegate is the same as the previous one, this does nothing.
@@ -424,15 +422,15 @@
/// delegate will be called.
///
/// If the new value is null, then there is no foreground custom painter.
- set foregroundPainter(CustomPainter value) {
+ set foregroundPainter(CustomPainter? value) {
if (_foregroundPainter == value)
return;
- final CustomPainter oldPainter = _foregroundPainter;
+ final CustomPainter? oldPainter = _foregroundPainter;
_foregroundPainter = value;
_didUpdatePainter(_foregroundPainter, oldPainter);
}
- void _didUpdatePainter(CustomPainter newPainter, CustomPainter oldPainter) {
+ void _didUpdatePainter(CustomPainter? newPainter, CustomPainter? oldPainter) {
// Check if we need to repaint.
if (newPainter == null) {
assert(oldPainter != null); // We should be called only for changes.
@@ -504,15 +502,15 @@
}
@override
- bool hitTestChildren(BoxHitTestResult result, { Offset position }) {
- if (_foregroundPainter != null && (_foregroundPainter.hitTest(position) ?? false))
+ bool hitTestChildren(BoxHitTestResult result, { required Offset position }) {
+ if (_foregroundPainter != null && (_foregroundPainter!.hitTest(position) ?? false))
return true;
return super.hitTestChildren(result, position: position);
}
@override
bool hitTestSelf(Offset position) {
- return _painter != null && (_painter.hitTest(position) ?? true);
+ return _painter != null && (_painter!.hitTest(position) ?? true);
}
@override
@@ -521,9 +519,8 @@
markNeedsSemanticsUpdate();
}
- void _paintWithPainter(Canvas canvas, Offset offset, CustomPainter/*!*/ painter) {
- // TODO(ianh): make the next line final
- /*late*/ int/*!*/ debugPreviousCanvasSaveCount;
+ void _paintWithPainter(Canvas canvas, Offset offset, CustomPainter painter) {
+ late int debugPreviousCanvasSaveCount;
canvas.save();
assert(() {
debugPreviousCanvasSaveCount = canvas.getSaveCount();
@@ -572,12 +569,12 @@
@override
void paint(PaintingContext context, Offset offset) {
if (_painter != null) {
- _paintWithPainter(context.canvas, offset, _painter);
+ _paintWithPainter(context.canvas, offset, _painter!);
_setRasterCacheHints(context);
}
super.paint(context, offset);
if (_foregroundPainter != null) {
- _paintWithPainter(context.canvas, offset, _foregroundPainter);
+ _paintWithPainter(context.canvas, offset, _foregroundPainter!);
_setRasterCacheHints(context);
}
}
@@ -590,10 +587,10 @@
}
/// Builds semantics for the picture drawn by [painter].
- SemanticsBuilderCallback _backgroundSemanticsBuilder;
+ SemanticsBuilderCallback? _backgroundSemanticsBuilder;
/// Builds semantics for the picture drawn by [foregroundPainter].
- SemanticsBuilderCallback _foregroundSemanticsBuilder;
+ SemanticsBuilderCallback? _foregroundSemanticsBuilder;
@override
void describeSemanticsConfiguration(SemanticsConfiguration config) {
@@ -604,10 +601,10 @@
}
/// Describe the semantics of the picture painted by the [painter].
- List<SemanticsNode/*!*/> _backgroundSemanticsNodes;
+ List<SemanticsNode>? _backgroundSemanticsNodes;
/// Describe the semantics of the picture painted by the [foregroundPainter].
- List<SemanticsNode/*!*/> _foregroundSemanticsNodes;
+ List<SemanticsNode>? _foregroundSemanticsNodes;
@override
void assembleSemanticsNode(
@@ -628,21 +625,21 @@
}());
final List<CustomPainterSemantics> backgroundSemantics = _backgroundSemanticsBuilder != null
- ? _backgroundSemanticsBuilder(size)
+ ? _backgroundSemanticsBuilder!(size)
: const <CustomPainterSemantics>[];
_backgroundSemanticsNodes = _updateSemanticsChildren(_backgroundSemanticsNodes, backgroundSemantics);
final List<CustomPainterSemantics> foregroundSemantics = _foregroundSemanticsBuilder != null
- ? _foregroundSemanticsBuilder(size)
+ ? _foregroundSemanticsBuilder!(size)
: const <CustomPainterSemantics>[];
_foregroundSemanticsNodes = _updateSemanticsChildren(_foregroundSemanticsNodes, foregroundSemantics);
- final bool hasBackgroundSemantics = _backgroundSemanticsNodes != null && _backgroundSemanticsNodes.isNotEmpty;
- final bool hasForegroundSemantics = _foregroundSemanticsNodes != null && _foregroundSemanticsNodes.isNotEmpty;
+ final bool hasBackgroundSemantics = _backgroundSemanticsNodes != null && _backgroundSemanticsNodes!.isNotEmpty;
+ final bool hasForegroundSemantics = _foregroundSemanticsNodes != null && _foregroundSemanticsNodes!.isNotEmpty;
final List<SemanticsNode> finalChildren = <SemanticsNode>[
- if (hasBackgroundSemantics) ..._backgroundSemanticsNodes,
+ if (hasBackgroundSemantics) ..._backgroundSemanticsNodes!,
...children,
- if (hasForegroundSemantics) ..._foregroundSemanticsNodes,
+ if (hasForegroundSemantics) ..._foregroundSemanticsNodes!,
];
super.assembleSemanticsNode(node, config, finalChildren);
}
@@ -676,23 +673,23 @@
/// considered because there is only one type of [SemanticsNode]. There is no
/// concept of a "forgotten" node in semantics, deactivated nodes, or global
/// keys.
- static List<SemanticsNode/*!*/> _updateSemanticsChildren(
- List<SemanticsNode> oldSemantics,
- List<CustomPainterSemantics> newChildSemantics,
+ static List<SemanticsNode> _updateSemanticsChildren(
+ List<SemanticsNode>? oldSemantics,
+ List<CustomPainterSemantics>? newChildSemantics,
) {
oldSemantics = oldSemantics ?? const <SemanticsNode>[];
newChildSemantics = newChildSemantics ?? const <CustomPainterSemantics>[];
assert(() {
- final Map<Key/*!*/, int> keys = HashMap<Key/*!*/, int>();
+ final Map<Key, int> keys = HashMap<Key, int>();
final List<DiagnosticsNode> information = <DiagnosticsNode>[];
- for (int i = 0; i < newChildSemantics.length; i += 1) {
+ for (int i = 0; i < newChildSemantics!.length; i += 1) {
final CustomPainterSemantics child = newChildSemantics[i];
if (child.key != null) {
if (keys.containsKey(child.key)) {
information.add(ErrorDescription('- duplicate key ${child.key} found at position $i'));
}
- keys[child.key] = i;
+ keys[child.key!] = i;
}
}
@@ -709,7 +706,7 @@
int newChildrenBottom = newChildSemantics.length - 1;
int oldChildrenBottom = oldSemantics.length - 1;
- final List<SemanticsNode/*!*/> newChildren = List<SemanticsNode/*!*/>(newChildSemantics.length);
+ final List<SemanticsNode?> newChildren = List<SemanticsNode?>.filled(newChildSemantics.length, null, growable: false);
// Update the top of the list.
while ((oldChildrenTop <= oldChildrenBottom) && (newChildrenTop <= newChildrenBottom)) {
@@ -735,23 +732,23 @@
// Scan the old children in the middle of the list.
final bool haveOldChildren = oldChildrenTop <= oldChildrenBottom;
- Map<Key/*!*/, SemanticsNode> oldKeyedChildren;
+ late final Map<Key, SemanticsNode> oldKeyedChildren;
if (haveOldChildren) {
oldKeyedChildren = <Key, SemanticsNode>{};
while (oldChildrenTop <= oldChildrenBottom) {
final SemanticsNode oldChild = oldSemantics[oldChildrenTop];
if (oldChild.key != null)
- oldKeyedChildren[oldChild.key] = oldChild;
+ oldKeyedChildren[oldChild.key!] = oldChild;
oldChildrenTop += 1;
}
}
// Update the middle of the list.
while (newChildrenTop <= newChildrenBottom) {
- SemanticsNode oldChild;
+ SemanticsNode? oldChild;
final CustomPainterSemantics newSemantics = newChildSemantics[newChildrenTop];
if (haveOldChildren) {
- final Key key = newSemantics.key;
+ final Key? key = newSemantics.key;
if (key != null) {
oldChild = oldKeyedChildren[key];
if (oldChild != null) {
@@ -793,13 +790,13 @@
}
assert(() {
- for (final SemanticsNode node in newChildren) {
+ for (final SemanticsNode? node in newChildren) {
assert(node != null);
}
return true;
}());
- return newChildren;
+ return newChildren.cast<SemanticsNode>();
}
/// Whether `oldChild` can be updated with properties from `newSemantics`.
@@ -814,7 +811,7 @@
///
/// This method requires that `_canUpdateSemanticsChild(oldChild, newSemantics)`
/// is true prior to calling it.
- static SemanticsNode _updateSemanticsChild(SemanticsNode oldChild, CustomPainterSemantics newSemantics) {
+ static SemanticsNode _updateSemanticsChild(SemanticsNode? oldChild, CustomPainterSemantics newSemantics) {
assert(oldChild == null || _canUpdateSemanticsChild(oldChild, newSemantics));
final SemanticsNode newChild = oldChild ?? SemanticsNode(
@@ -830,52 +827,52 @@
config.isChecked = properties.checked;
}
if (properties.selected != null) {
- config.isSelected = properties.selected;
+ config.isSelected = properties.selected!;
}
if (properties.button != null) {
- config.isButton = properties.button;
+ config.isButton = properties.button!;
}
if (properties.link != null) {
- config.isLink = properties.link;
+ config.isLink = properties.link!;
}
if (properties.textField != null) {
- config.isTextField = properties.textField;
+ config.isTextField = properties.textField!;
}
if (properties.readOnly != null) {
- config.isReadOnly = properties.readOnly;
+ config.isReadOnly = properties.readOnly!;
}
if (properties.focusable != null) {
- config.isFocusable = properties.focusable;
+ config.isFocusable = properties.focusable!;
}
if (properties.focused != null) {
- config.isFocused = properties.focused;
+ config.isFocused = properties.focused!;
}
if (properties.enabled != null) {
config.isEnabled = properties.enabled;
}
if (properties.inMutuallyExclusiveGroup != null) {
- config.isInMutuallyExclusiveGroup = properties.inMutuallyExclusiveGroup;
+ config.isInMutuallyExclusiveGroup = properties.inMutuallyExclusiveGroup!;
}
if (properties.obscured != null) {
- config.isObscured = properties.obscured;
+ config.isObscured = properties.obscured!;
}
if (properties.multiline != null) {
- config.isMultiline = properties.multiline;
+ config.isMultiline = properties.multiline!;
}
if (properties.hidden != null) {
- config.isHidden = properties.hidden;
+ config.isHidden = properties.hidden!;
}
if (properties.header != null) {
- config.isHeader = properties.header;
+ config.isHeader = properties.header!;
}
if (properties.scopesRoute != null) {
- config.scopesRoute = properties.scopesRoute;
+ config.scopesRoute = properties.scopesRoute!;
}
if (properties.namesRoute != null) {
- config.namesRoute = properties.namesRoute;
+ config.namesRoute = properties.namesRoute!;
}
if (properties.liveRegion != null) {
- config.liveRegion = properties.liveRegion;
+ config.liveRegion = properties.liveRegion!;
}
if (properties.maxValueLength != null) {
config.maxValueLength = properties.maxValueLength;
@@ -887,22 +884,22 @@
config.isToggled = properties.toggled;
}
if (properties.image != null) {
- config.isImage = properties.image;
+ config.isImage = properties.image!;
}
if (properties.label != null) {
- config.label = properties.label;
+ config.label = properties.label!;
}
if (properties.value != null) {
- config.value = properties.value;
+ config.value = properties.value!;
}
if (properties.increasedValue != null) {
- config.increasedValue = properties.increasedValue;
+ config.increasedValue = properties.increasedValue!;
}
if (properties.decreasedValue != null) {
- config.decreasedValue = properties.decreasedValue;
+ config.decreasedValue = properties.decreasedValue!;
}
if (properties.hint != null) {
- config.hint = properties.hint;
+ config.hint = properties.hint!;
}
if (properties.textDirection != null) {
config.textDirection = properties.textDirection;
diff --git a/packages/flutter/lib/src/rendering/debug.dart b/packages/flutter/lib/src/rendering/debug.dart
index 1208258..3b9d29b 100644
--- a/packages/flutter/lib/src/rendering/debug.dart
+++ b/packages/flutter/lib/src/rendering/debug.dart
@@ -2,8 +2,6 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-// @dart = 2.8
-
import 'package:flutter/foundation.dart';
import 'package:flutter/painting.dart';
@@ -88,6 +86,11 @@
///
/// This check helps developers that want a consistent look and feel detect
/// where this inconsistency would occur.
+///
+/// This check assumes that elevations on [PhysicalModelLayer] objects have
+/// been set to non-null values before the scene is built. If this assumption
+/// is violated, the check will throw exceptions. (The scene building would
+/// also fail in that case, however.)
bool debugCheckElevationsEnabled = false;
/// The current color to overlay when repainting a layer.
@@ -174,7 +177,7 @@
bool debugProfilePaintsEnabled = false;
/// Signature for [debugOnProfilePaint] implementations.
-typedef ProfilePaintCallback = void Function(RenderObject/*!*/ renderObject);
+typedef ProfilePaintCallback = void Function(RenderObject renderObject);
/// Callback invoked for every [RenderObject] painted each frame.
///
@@ -190,7 +193,7 @@
/// callback to generate aggregate profile statistics describing what paints
/// occurred when the `ext.flutter.inspector.trackRepaintWidgets` service
/// extension is enabled.
-ProfilePaintCallback debugOnProfilePaint;
+ProfilePaintCallback? debugOnProfilePaint;
/// Setting to true will cause all clipping effects from the layer tree to be
/// ignored.
@@ -243,7 +246,7 @@
///
/// Called by [RenderPadding.debugPaintSize] when [debugPaintSizeEnabled] is
/// true.
-void debugPaintPadding(Canvas canvas, Rect outerRect, Rect innerRect, { double outlineWidth = 2.0 }) {
+void debugPaintPadding(Canvas canvas, Rect outerRect, Rect? innerRect, { double outlineWidth = 2.0 }) {
assert(() {
if (innerRect != null && !innerRect.isEmpty) {
_debugDrawDoubleRect(canvas, outerRect, innerRect, const Color(0x900090FF));
diff --git a/packages/flutter/lib/src/rendering/debug_overflow_indicator.dart b/packages/flutter/lib/src/rendering/debug_overflow_indicator.dart
index 73cfac1..dae3c0c 100644
--- a/packages/flutter/lib/src/rendering/debug_overflow_indicator.dart
+++ b/packages/flutter/lib/src/rendering/debug_overflow_indicator.dart
@@ -2,8 +2,6 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-// @dart = 2.8
-
import 'dart:math' as math;
import 'dart:ui' as ui;
@@ -25,11 +23,11 @@
// the indicators.
class _OverflowRegionData {
const _OverflowRegionData({
- this.rect,
+ required this.rect,
this.label = '',
this.labelOffset = Offset.zero,
this.rotation = 0.0,
- this.side,
+ required this.side,
});
final Rect rect;
@@ -201,7 +199,7 @@
return regions;
}
- void _reportOverflow(RelativeRect overflow, List<DiagnosticsNode> overflowHints) {
+ void _reportOverflow(RelativeRect overflow, List<DiagnosticsNode>? overflowHints) {
overflowHints ??= <DiagnosticsNode>[];
if (overflowHints.isEmpty) {
overflowHints.add(ErrorDescription(
@@ -248,8 +246,8 @@
context: ErrorDescription('during layout'),
informationCollector: () sync* {
if (debugCreator != null)
- yield DiagnosticsDebugCreator(debugCreator);
- yield* overflowHints;
+ yield DiagnosticsDebugCreator(debugCreator as Object);
+ yield* overflowHints!;
yield describeForError('The specific $runtimeType in question is');
// TODO(jacobr): this line is ascii art that it would be nice to
// handle a little more generically in GUI debugging clients in the
@@ -271,7 +269,7 @@
Offset offset,
Rect containerRect,
Rect childRect, {
- List<DiagnosticsNode> overflowHints,
+ List<DiagnosticsNode>? overflowHints,
}) {
final RelativeRect overflow = RelativeRect.fromRect(containerRect, childRect);
@@ -285,7 +283,7 @@
final List<_OverflowRegionData> overflowRegions = _calculateOverflowRegions(overflow, containerRect);
for (final _OverflowRegionData region in overflowRegions) {
context.canvas.drawRect(region.rect.shift(offset), _indicatorPaint);
- final TextSpan textSpan = _indicatorLabel[region.side.index].text as TextSpan;
+ final TextSpan? textSpan = _indicatorLabel[region.side.index].text as TextSpan?;
if (textSpan?.text != region.label) {
_indicatorLabel[region.side.index].text = TextSpan(
text: region.label,
diff --git a/packages/flutter/lib/src/rendering/editable.dart b/packages/flutter/lib/src/rendering/editable.dart
index 62d67bb..c0e975b 100644
--- a/packages/flutter/lib/src/rendering/editable.dart
+++ b/packages/flutter/lib/src/rendering/editable.dart
@@ -2,8 +2,6 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-// @dart = 2.8
-
import 'dart:math' as math;
import 'dart:ui' as ui show TextBox, lerpDouble, BoxHeightStyle, BoxWidthStyle;
@@ -86,7 +84,7 @@
final Offset point;
/// Direction of the text at this edge of the selection.
- final TextDirection direction;
+ final TextDirection? direction;
@override
String toString() {
@@ -95,8 +93,9 @@
return '$point-ltr';
case TextDirection.rtl:
return '$point-rtl';
+ case null:
+ return '$point';
}
- return '$point';
}
}
@@ -181,47 +180,47 @@
/// The [offset] is required and must not be null. You can use [new
/// ViewportOffset.zero] if you have no need for scrolling.
RenderEditable({
- TextSpan text,
- @required TextDirection textDirection,
+ TextSpan? text,
+ required TextDirection textDirection,
TextAlign textAlign = TextAlign.start,
- Color cursorColor,
- Color backgroundCursorColor,
- ValueNotifier<bool> showCursor,
- bool hasFocus,
- @required LayerLink startHandleLayerLink,
- @required LayerLink endHandleLayerLink,
- int maxLines = 1,
- int minLines,
+ Color? cursorColor,
+ Color? backgroundCursorColor,
+ ValueNotifier<bool>? showCursor,
+ bool? hasFocus,
+ required LayerLink startHandleLayerLink,
+ required LayerLink endHandleLayerLink,
+ int? maxLines = 1,
+ int? minLines,
bool expands = false,
- StrutStyle strutStyle,
- Color selectionColor,
+ StrutStyle? strutStyle,
+ Color? selectionColor,
double textScaleFactor = 1.0,
- TextSelection selection,
- @required ViewportOffset offset,
+ TextSelection? selection,
+ required ViewportOffset offset,
this.onSelectionChanged,
this.onCaretChanged,
this.ignorePointer = false,
bool readOnly = false,
bool forceLine = true,
- TextHeightBehavior textHeightBehavior,
+ TextHeightBehavior? textHeightBehavior,
TextWidthBasis textWidthBasis = TextWidthBasis.parent,
String obscuringCharacter = '•',
bool obscureText = false,
- Locale locale,
+ Locale? locale,
double cursorWidth = 1.0,
- double cursorHeight,
- Radius cursorRadius,
+ double? cursorHeight,
+ Radius? cursorRadius,
bool paintCursorAboveText = false,
- Offset cursorOffset,
+ Offset? cursorOffset,
double devicePixelRatio = 1.0,
ui.BoxHeightStyle selectionHeightStyle = ui.BoxHeightStyle.tight,
ui.BoxWidthStyle selectionWidthStyle = ui.BoxWidthStyle.tight,
- bool enableInteractiveSelection,
+ bool? enableInteractiveSelection,
EdgeInsets floatingCursorAddedMargin = const EdgeInsets.fromLTRB(4, 4, 4, 5),
- TextRange promptRectRange,
- Color promptRectColor,
+ TextRange? promptRectRange,
+ Color? promptRectColor,
Clip clipBehavior = Clip.hardEdge,
- @required this.textSelectionDelegate,
+ required this.textSelectionDelegate,
}) : assert(textAlign != null),
assert(textDirection != null, 'RenderEditable created without a textDirection.'),
assert(maxLines == null || maxLines > 0),
@@ -300,13 +299,13 @@
/// Called when the selection changes.
///
/// If this is null, then selection changes will be ignored.
- SelectionChangedHandler onSelectionChanged;
+ SelectionChangedHandler? onSelectionChanged;
- double _textLayoutLastMaxWidth;
- double _textLayoutLastMinWidth;
+ double? _textLayoutLastMaxWidth;
+ double? _textLayoutLastMinWidth;
/// Called during the paint phase when the caret location changes.
- CaretChangedHandler onCaretChanged;
+ CaretChangedHandler? onCaretChanged;
/// Whether the [handleEvent] will propagate pointer events to selection
/// handlers.
@@ -322,8 +321,8 @@
bool ignorePointer;
/// {@macro flutter.dart:ui.textHeightBehavior}
- TextHeightBehavior get textHeightBehavior => _textPainter.textHeightBehavior;
- set textHeightBehavior(TextHeightBehavior value) {
+ TextHeightBehavior? get textHeightBehavior => _textPainter.textHeightBehavior;
+ set textHeightBehavior(TextHeightBehavior? value) {
if (_textPainter.textHeightBehavior == value)
return;
_textPainter.textHeightBehavior = value;
@@ -383,7 +382,7 @@
/// with the most recently set [TextSelectionDelegate].
TextSelectionDelegate textSelectionDelegate;
- Rect _lastCaretRect;
+ Rect? _lastCaretRect;
/// Track whether position of the start of the selected text is within the viewport.
///
@@ -416,7 +415,7 @@
final Rect visibleRegion = Offset.zero & size;
final Offset startOffset = _textPainter.getOffsetForCaret(
- TextPosition(offset: selection.start, affinity: selection.affinity),
+ TextPosition(offset: selection!.start, affinity: selection!.affinity),
_caretPrototype,
);
// TODO(justinmc): https://github.com/flutter/flutter/issues/31495
@@ -432,7 +431,7 @@
.contains(startOffset + effectiveOffset);
final Offset endOffset = _textPainter.getOffsetForCaret(
- TextPosition(offset: selection.end, affinity: selection.affinity),
+ TextPosition(offset: selection!.end, affinity: selection!.affinity),
_caretPrototype,
);
_selectionEndInViewport.value = visibleRegion
@@ -468,7 +467,7 @@
return;
}
if (onSelectionChanged != null) {
- onSelectionChanged(nextSelection, this, cause);
+ onSelectionChanged!(nextSelection, this, cause);
}
}
@@ -600,7 +599,7 @@
}
int count = 0;
- int lastNonWhitespace;
+ int? lastNonWhitespace;
for (final String currentString in string.characters) {
if (!includeWhitespace &&
!_isWhitespace(currentString.characters.first.toString().codeUnitAt(0))) {
@@ -616,17 +615,17 @@
void _handleMovement(
LogicalKeyboardKey key, {
- @required bool wordModifier,
- @required bool lineModifier,
- @required bool shift,
- }) {
+ required bool wordModifier,
+ required bool lineModifier,
+ required bool shift,
+ }){
if (wordModifier && lineModifier) {
// If both modifiers are down, nothing happens on any of the platforms.
return;
}
assert(selection != null);
- TextSelection/*!*/ newSelection = selection;
+ TextSelection newSelection = selection!;
final bool rightArrow = key == LogicalKeyboardKey.arrowRight;
final bool leftArrow = key == LogicalKeyboardKey.arrowLeft;
@@ -734,7 +733,7 @@
// We want to put the cursor at the correct location depending on which
// arrow is used while there is a selection.
int newOffset = newSelection.extentOffset;
- if (!selection.isCollapsed) {
+ if (!selection!.isCollapsed) {
if (leftArrow) {
newOffset = newSelection.baseOffset < newSelection.extentOffset ? newSelection.baseOffset : newSelection.extentOffset;
} else if (rightArrow) {
@@ -758,19 +757,19 @@
assert(selection != null);
assert(_shortcutKeys.contains(key), 'shortcut key $key not recognized.');
if (key == LogicalKeyboardKey.keyC) {
- if (!selection.isCollapsed) {
+ if (!selection!.isCollapsed) {
Clipboard.setData(
- ClipboardData(text: selection.textInside(_plainText)));
+ ClipboardData(text: selection!.textInside(_plainText)));
}
return;
}
if (key == LogicalKeyboardKey.keyX) {
- if (!selection.isCollapsed) {
- Clipboard.setData(ClipboardData(text: selection.textInside(_plainText)));
+ if (!selection!.isCollapsed) {
+ Clipboard.setData(ClipboardData(text: selection!.textInside(_plainText)));
textSelectionDelegate.textEditingValue = TextEditingValue(
- text: selection.textBefore(_plainText)
- + selection.textAfter(_plainText),
- selection: TextSelection.collapsed(offset: selection.start),
+ text: selection!.textBefore(_plainText)
+ + selection!.textAfter(_plainText),
+ selection: TextSelection.collapsed(offset: selection!.start),
);
}
return;
@@ -779,14 +778,14 @@
// Snapshot the input before using `await`.
// See https://github.com/flutter/flutter/issues/11427
final TextEditingValue value = textSelectionDelegate.textEditingValue;
- final ClipboardData data = await Clipboard.getData(Clipboard.kTextPlain);
+ final ClipboardData? data = await Clipboard.getData(Clipboard.kTextPlain);
if (data != null) {
textSelectionDelegate.textEditingValue = TextEditingValue(
text: value.selection.textBefore(value.text)
- + data.text
+ + data.text!
+ value.selection.textAfter(value.text),
selection: TextSelection.collapsed(
- offset: value.selection.start + data.text.length
+ offset: value.selection.start + data.text!.length
),
);
}
@@ -794,7 +793,7 @@
}
if (key == LogicalKeyboardKey.keyA) {
_handleSelectionChange(
- selection.copyWith(
+ selection!.copyWith(
baseOffset: 0,
extentOffset: textSelectionDelegate.textEditingValue.text.length,
),
@@ -806,18 +805,18 @@
void _handleDelete() {
assert(_selection != null);
- final String textAfter = selection.textAfter(_plainText);
+ final String textAfter = selection!.textAfter(_plainText);
if (textAfter.isNotEmpty) {
final int deleteCount = nextCharacter(0, textAfter);
textSelectionDelegate.textEditingValue = TextEditingValue(
- text: selection.textBefore(_plainText)
- + selection.textAfter(_plainText).substring(deleteCount),
- selection: TextSelection.collapsed(offset: selection.start),
+ text: selection!.textBefore(_plainText)
+ + selection!.textAfter(_plainText).substring(deleteCount),
+ selection: TextSelection.collapsed(offset: selection!.start),
);
} else {
textSelectionDelegate.textEditingValue = TextEditingValue(
- text: selection.textBefore(_plainText),
- selection: TextSelection.collapsed(offset: selection.start),
+ text: selection!.textBefore(_plainText),
+ selection: TextSelection.collapsed(offset: selection!.start),
);
}
}
@@ -842,16 +841,16 @@
}
// Returns a cached plain text version of the text in the painter.
- String _cachedPlainText;
- String/*!*/ get _plainText {
- _cachedPlainText ??= _textPainter.text.toPlainText();
- return _cachedPlainText;
+ String? _cachedPlainText;
+ String get _plainText {
+ _cachedPlainText ??= _textPainter.text!.toPlainText();
+ return _cachedPlainText!;
}
/// The text to display.
- TextSpan get text => _textPainter.text as TextSpan;
+ TextSpan? get text => _textPainter.text as TextSpan?;
final TextPainter _textPainter;
- set text(TextSpan/*?*/ value) {
+ set text(TextSpan? value) {
if (_textPainter.text == value)
return;
_textPainter.text = value;
@@ -888,7 +887,7 @@
// TextPainter.textDirection is nullable, but it is set to a
// non-null value in the RenderEditable constructor and we refuse to
// set it to null here, so _textPainter.textDirection cannot be null.
- TextDirection get textDirection => _textPainter.textDirection/*!*/;
+ TextDirection get textDirection => _textPainter.textDirection!;
set textDirection(TextDirection value) {
assert(value != null);
if (_textPainter.textDirection == value)
@@ -908,8 +907,8 @@
///
/// If this value is null, a system-dependent algorithm is used to select
/// the font.
- Locale get locale => _textPainter.locale;
- set locale(Locale value) {
+ Locale? get locale => _textPainter.locale;
+ set locale(Locale? value) {
if (_textPainter.locale == value)
return;
_textPainter.locale = value;
@@ -918,8 +917,8 @@
/// The [StrutStyle] used by the renderer's internal [TextPainter] to
/// determine the strut to use.
- StrutStyle get strutStyle => _textPainter.strutStyle;
- set strutStyle(StrutStyle value) {
+ StrutStyle? get strutStyle => _textPainter.strutStyle;
+ set strutStyle(StrutStyle? value) {
if (_textPainter.strutStyle == value)
return;
_textPainter.strutStyle = value;
@@ -927,9 +926,9 @@
}
/// The color to use when painting the cursor.
- Color get cursorColor => _cursorColor;
- Color _cursorColor;
- set cursorColor(Color value) {
+ Color? get cursorColor => _cursorColor;
+ Color? _cursorColor;
+ set cursorColor(Color? value) {
if (_cursorColor == value)
return;
_cursorColor = value;
@@ -940,9 +939,9 @@
/// rendering the floating cursor.
///
/// The default is light grey.
- Color get backgroundCursorColor => _backgroundCursorColor;
- Color _backgroundCursorColor;
- set backgroundCursorColor(Color value) {
+ Color? get backgroundCursorColor => _backgroundCursorColor;
+ Color? _backgroundCursorColor;
+ set backgroundCursorColor(Color? value) {
if (backgroundCursorColor == value)
return;
_backgroundCursorColor = value;
@@ -1017,10 +1016,10 @@
/// When this is not null, the intrinsic height of the render object is the
/// height of one line of text multiplied by this value. In other words, this
/// also controls the height of the actual editing widget.
- int get maxLines => _maxLines;
- int _maxLines;
+ int? get maxLines => _maxLines;
+ int? _maxLines;
/// The value may be null. If it is not null, then it must be greater than zero.
- set maxLines(int value) {
+ set maxLines(int? value) {
assert(value == null || value > 0);
if (maxLines == value)
return;
@@ -1029,10 +1028,10 @@
}
/// {@macro flutter.widgets.editableText.minLines}
- int get minLines => _minLines;
- int _minLines;
+ int? get minLines => _minLines;
+ int? _minLines;
/// The value may be null. If it is not null, then it must be greater than zero.
- set minLines(int value) {
+ set minLines(int? value) {
assert(value == null || value > 0);
if (minLines == value)
return;
@@ -1052,9 +1051,9 @@
}
/// The color to use when painting the selection.
- Color get selectionColor => _selectionColor;
- Color _selectionColor;
- set selectionColor(Color value) {
+ Color? get selectionColor => _selectionColor;
+ Color? _selectionColor;
+ set selectionColor(Color? value) {
if (_selectionColor == value)
return;
_selectionColor = value;
@@ -1074,7 +1073,7 @@
markNeedsTextLayout();
}
- List<ui.TextBox> _selectionRects;
+ List<ui.TextBox>? _selectionRects;
/// The region of text that is selected, if any.
///
@@ -1082,9 +1081,9 @@
///
/// If [selection] is null, there is no selection and attempts to
/// manipulate the selection will throw.
- TextSelection get selection => _selection;
- TextSelection _selection;
- set selection(TextSelection value) {
+ TextSelection? get selection => _selection;
+ TextSelection? _selection;
+ set selection(TextSelection? value) {
if (_selection == value)
return;
_selection = value;
@@ -1123,9 +1122,15 @@
}
/// How tall the cursor will be.
+ ///
+ /// This can be null, in which case the getter will actually return [preferredLineHeight].
+ ///
+ /// Setting this to itself fixes the value to the current [preferredLineHeight]. Setting
+ /// this to null returns the behaviour of deferring to [preferredLineHeight].
+ // TODO(ianh): This is a confusing API. We should have a separate getter for the effective cursor height.
double get cursorHeight => _cursorHeight ?? preferredLineHeight;
- double _cursorHeight;
- set cursorHeight(double value) {
+ double? _cursorHeight;
+ set cursorHeight(double? value) {
if (_cursorHeight == value)
return;
_cursorHeight = value;
@@ -1155,9 +1160,9 @@
/// platforms. The origin from where the offset is applied to is the arbitrary
/// location where the cursor ends up being rendered from by default.
/// {@endtemplate}
- Offset get cursorOffset => _cursorOffset;
- Offset _cursorOffset;
- set cursorOffset(Offset value) {
+ Offset? get cursorOffset => _cursorOffset;
+ Offset? _cursorOffset;
+ set cursorOffset(Offset? value) {
if (_cursorOffset == value)
return;
_cursorOffset = value;
@@ -1165,9 +1170,11 @@
}
/// How rounded the corners of the cursor should be.
- Radius get cursorRadius => _cursorRadius;
- Radius _cursorRadius;
- set cursorRadius(Radius value) {
+ ///
+ /// A null value is the same as [Radius.zero].
+ Radius? get cursorRadius => _cursorRadius;
+ Radius? _cursorRadius;
+ set cursorRadius(Radius? value) {
if (_cursorRadius == value)
return;
_cursorRadius = value;
@@ -1214,8 +1221,8 @@
}
bool _floatingCursorOn = false;
- Offset _floatingCursorOffset;
- TextPosition _floatingCursorTextPosition;
+ late Offset _floatingCursorOffset;
+ late TextPosition _floatingCursorTextPosition;
/// Controls how tall the selection highlight boxes are computed to be.
///
@@ -1256,9 +1263,9 @@
/// the accessibility hints mentioned above). When null,
/// [obscureText] is used to determine the value of
/// [selectionEnabled] instead.
- bool get enableInteractiveSelection => _enableInteractiveSelection;
- bool _enableInteractiveSelection;
- set enableInteractiveSelection(bool/*?*/ value) {
+ bool? get enableInteractiveSelection => _enableInteractiveSelection;
+ bool? _enableInteractiveSelection;
+ set enableInteractiveSelection(bool? value) {
if (_enableInteractiveSelection == value)
return;
_enableInteractiveSelection = value;
@@ -1296,8 +1303,8 @@
// TODO(ianh): We should change the getter to return null when _promptRectRange is null
// (otherwise, if you set it to null and then get it, you get back non-null).
// Alternatively, we could stop supporting setting this to null.
- Color/*?*/ get promptRectColor => _promptRectPaint.color;
- set promptRectColor(Color/*?*/ newValue) {
+ Color? get promptRectColor => _promptRectPaint.color;
+ set promptRectColor(Color? newValue) {
// Painter.color cannot be null.
if (newValue == null) {
setPromptRectRange(null);
@@ -1312,14 +1319,14 @@
markNeedsPaint();
}
- TextRange _promptRectRange;
+ TextRange? _promptRectRange;
/// Dismisses the currently displayed prompt rectangle and displays a new prompt rectangle
/// over [newRange] in the given color [promptRectColor].
///
/// The prompt rectangle will only be requested on non-web iOS applications.
///
/// When set to null, the currently displayed prompt rectangle (if any) will be dismissed.
- void setPromptRectRange(TextRange/*?*/ newRange) {
+ void setPromptRectRange(TextRange? newRange) {
if (_promptRectRange == newRange)
return;
@@ -1333,7 +1340,7 @@
/// text is entered or removed in order to accommodate expanding when
/// [expands] is set to true.
double get maxScrollExtent => _maxScrollExtent;
- double/*!*/ _maxScrollExtent = 0;
+ double _maxScrollExtent = 0;
double get _caretMargin => _kCaretGap + cursorWidth;
@@ -1371,12 +1378,12 @@
if (selectionEnabled && selection?.isValid == true) {
config.textSelection = selection;
- if (_textPainter.getOffsetBefore(selection.extentOffset) != null) {
+ if (_textPainter.getOffsetBefore(selection!.extentOffset) != null) {
config
..onMoveCursorBackwardByWord = _handleMoveCursorBackwardByWord
..onMoveCursorBackwardByCharacter = _handleMoveCursorBackwardByCharacter;
}
- if (_textPainter.getOffsetAfter(selection.extentOffset) != null) {
+ if (_textPainter.getOffsetAfter(selection!.extentOffset) != null) {
config
..onMoveCursorForwardByWord = _handleMoveCursorForwardByWord
..onMoveCursorForwardByCharacter = _handleMoveCursorForwardByCharacter;
@@ -1394,10 +1401,10 @@
void _handleMoveCursorForwardByCharacter(bool extentSelection) {
assert(selection != null);
- final int extentOffset = _textPainter.getOffsetAfter(selection.extentOffset);
+ final int? extentOffset = _textPainter.getOffsetAfter(selection!.extentOffset);
if (extentOffset == null)
return;
- final int baseOffset = !extentSelection ? extentOffset : selection.baseOffset;
+ final int baseOffset = !extentSelection ? extentOffset : selection!.baseOffset;
_handleSelectionChange(
TextSelection(baseOffset: baseOffset, extentOffset: extentOffset), SelectionChangedCause.keyboard,
);
@@ -1405,10 +1412,10 @@
void _handleMoveCursorBackwardByCharacter(bool extentSelection) {
assert(selection != null);
- final int extentOffset = _textPainter.getOffsetBefore(selection.extentOffset);
+ final int? extentOffset = _textPainter.getOffsetBefore(selection!.extentOffset);
if (extentOffset == null)
return;
- final int baseOffset = !extentSelection ? extentOffset : selection.baseOffset;
+ final int baseOffset = !extentSelection ? extentOffset : selection!.baseOffset;
_handleSelectionChange(
TextSelection(baseOffset: baseOffset, extentOffset: extentOffset), SelectionChangedCause.keyboard,
);
@@ -1416,13 +1423,11 @@
void _handleMoveCursorForwardByWord(bool extentSelection) {
assert(selection != null);
- final TextRange currentWord = _textPainter.getWordBoundary(selection.extent);
- if (currentWord == null)
- return;
- final TextRange nextWord = _getNextWord(currentWord.end);
+ final TextRange currentWord = _textPainter.getWordBoundary(selection!.extent);
+ final TextRange? nextWord = _getNextWord(currentWord.end);
if (nextWord == null)
return;
- final int baseOffset = extentSelection ? selection.baseOffset : nextWord.start;
+ final int baseOffset = extentSelection ? selection!.baseOffset : nextWord.start;
_handleSelectionChange(
TextSelection(
baseOffset: baseOffset,
@@ -1434,13 +1439,11 @@
void _handleMoveCursorBackwardByWord(bool extentSelection) {
assert(selection != null);
- final TextRange currentWord = _textPainter.getWordBoundary(selection.extent);
- if (currentWord == null)
- return;
- final TextRange previousWord = _getPreviousWord(currentWord.start - 1);
+ final TextRange currentWord = _textPainter.getWordBoundary(selection!.extent);
+ final TextRange? previousWord = _getPreviousWord(currentWord.start - 1);
if (previousWord == null)
return;
- final int baseOffset = extentSelection ? selection.baseOffset : previousWord.start;
+ final int baseOffset = extentSelection ? selection!.baseOffset : previousWord.start;
_handleSelectionChange(
TextSelection(
baseOffset: baseOffset,
@@ -1450,7 +1453,7 @@
);
}
- TextRange _getNextWord(int offset) {
+ TextRange? _getNextWord(int offset) {
while (true) {
final TextRange range = _textPainter.getWordBoundary(TextPosition(offset: offset));
if (range == null || !range.isValid || range.isCollapsed)
@@ -1461,7 +1464,7 @@
}
}
- TextRange _getPreviousWord(int offset) {
+ TextRange? _getPreviousWord(int offset) {
while (offset >= 0) {
final TextRange range = _textPainter.getWordBoundary(TextPosition(offset: offset));
if (range == null || !range.isValid || range.isCollapsed)
@@ -1481,7 +1484,7 @@
// TODO(jonahwilliams): replace when we expose this ICU information.
bool _onlyWhitespace(TextRange range) {
for (int i = range.start; i < range.end; i++) {
- final int/*!*/ codeUnit = text.codeUnitAt(i);
+ final int codeUnit = text!.codeUnitAt(i)!;
if (!_isWhitespace(codeUnit)) {
return false;
}
@@ -1515,17 +1518,16 @@
Axis get _viewportAxis => _isMultiline ? Axis.vertical : Axis.horizontal;
- Offset/*!*/ get _paintOffset {
+ Offset get _paintOffset {
switch (_viewportAxis) {
case Axis.horizontal:
return Offset(-offset.pixels, 0.0);
case Axis.vertical:
return Offset(0.0, -offset.pixels);
}
- return null;
}
- double/*!*/ get _viewportExtent {
+ double get _viewportExtent {
assert(hasSize);
switch (_viewportAxis) {
case Axis.horizontal:
@@ -1533,10 +1535,9 @@
case Axis.vertical:
return size.height;
}
- return null;
}
- double/*!*/ _getMaxScrollExtent(Size contentSize) {
+ double _getMaxScrollExtent(Size contentSize) {
assert(hasSize);
switch (_viewportAxis) {
case Axis.horizontal:
@@ -1544,7 +1545,6 @@
case Axis.vertical:
return math.max(0.0, contentSize.height - size.height);
}
- return null;
}
// We need to check the paint offset here because during animation, the start of
@@ -1619,7 +1619,7 @@
Rect rect = Rect.fromLTWH(0.0, 0.0, cursorWidth, cursorHeight).shift(caretOffset + _paintOffset);
// Add additional cursor offset (generally only if on iOS).
if (_cursorOffset != null)
- rect = rect.shift(_cursorOffset);
+ rect = rect.shift(_cursorOffset!);
return rect.shift(_getPixelPerfectCursorOffset(rect));
}
@@ -1646,19 +1646,19 @@
final bool lockedBoth = minLines != null && minLines == maxLines;
final bool singleLine = maxLines == 1;
if (singleLine || lockedMax || lockedBoth) {
- return preferredLineHeight * maxLines;
+ return preferredLineHeight * maxLines!;
}
// Clamp height to minLines or maxLines if needed.
- final bool minLimited = minLines != null && minLines > 1;
+ final bool minLimited = minLines != null && minLines! > 1;
final bool maxLimited = maxLines != null;
if (minLimited || maxLimited) {
_layoutText(maxWidth: width);
- if (minLimited && _textPainter.height < preferredLineHeight * minLines) {
- return preferredLineHeight * minLines;
+ if (minLimited && _textPainter.height < preferredLineHeight * minLines!) {
+ return preferredLineHeight * minLines!;
}
- if (maxLimited && _textPainter.height > preferredLineHeight * maxLines) {
- return preferredLineHeight * maxLines;
+ if (maxLimited && _textPainter.height > preferredLineHeight * maxLines!) {
+ return preferredLineHeight * maxLines!;
}
}
@@ -1695,8 +1695,8 @@
@override
bool hitTestSelf(Offset position) => true;
- TapGestureRecognizer _tap;
- LongPressGestureRecognizer _longPress;
+ late TapGestureRecognizer _tap;
+ late LongPressGestureRecognizer _longPress;
@override
void handleEvent(PointerEvent event, BoxHitTestEntry entry) {
@@ -1706,7 +1706,7 @@
// Checks if there is any gesture recognizer in the text span.
final Offset offset = entry.localPosition;
final TextPosition position = _textPainter.getPositionForOffset(offset);
- final InlineSpan span = _textPainter.text.getSpanForPosition(position);
+ final InlineSpan? span = _textPainter.text!.getSpanForPosition(position);
if (span != null && span is TextSpan) {
final TextSpan textSpan = span;
textSpan.recognizer?.addPointer(event);
@@ -1720,7 +1720,7 @@
}
}
- Offset _lastTapDownPosition;
+ Offset? _lastTapDownPosition;
/// If [ignorePointer] is false (the default) then this method is called by
/// the internal gesture recognizer's [TapGestureRecognizer.onTapDown]
@@ -1784,12 +1784,12 @@
/// If you have a [TextEditingController], it's generally easier to
/// programmatically manipulate its `value` or `selection` directly.
/// {@endtemplate}
- void selectPosition({ @required SelectionChangedCause cause }) {
- selectPositionAt(from: _lastTapDownPosition, cause: cause);
+ void selectPosition({ required SelectionChangedCause cause }) {
+ selectPositionAt(from: _lastTapDownPosition!, cause: cause);
}
/// Select text between the global positions [from] and [to].
- void selectPositionAt({ @required Offset from, Offset to, @required SelectionChangedCause cause }) {
+ void selectPositionAt({ required Offset from, Offset? to, required SelectionChangedCause cause }) {
assert(cause != null);
assert(from != null);
_layoutText(minWidth: constraints.minWidth, maxWidth: constraints.maxWidth);
@@ -1797,7 +1797,7 @@
return;
}
final TextPosition fromPosition = _textPainter.getPositionForOffset(globalToLocal(from - _paintOffset));
- final TextPosition toPosition = to == null
+ final TextPosition? toPosition = to == null
? null
: _textPainter.getPositionForOffset(globalToLocal(to - _paintOffset));
@@ -1820,8 +1820,8 @@
/// Select a word around the location of the last tap down.
///
/// {@macro flutter.rendering.editable.select}
- void selectWord({ @required SelectionChangedCause cause }) {
- selectWordsInRange(from: _lastTapDownPosition, cause: cause);
+ void selectWord({ required SelectionChangedCause cause }) {
+ selectWordsInRange(from: _lastTapDownPosition!, cause: cause);
}
/// Selects the set words of a paragraph in a given range of global positions.
@@ -1830,7 +1830,7 @@
/// beginning and end of a word respectively.
///
/// {@macro flutter.rendering.editable.select}
- void selectWordsInRange({ @required Offset from, Offset to, @required SelectionChangedCause cause }) {
+ void selectWordsInRange({ required Offset from, Offset? to, required SelectionChangedCause cause }) {
assert(cause != null);
assert(from != null);
_layoutText(minWidth: constraints.minWidth, maxWidth: constraints.maxWidth);
@@ -1855,14 +1855,14 @@
/// Move the selection to the beginning or end of a word.
///
/// {@macro flutter.rendering.editable.select}
- void selectWordEdge({ @required SelectionChangedCause cause }) {
+ void selectWordEdge({ required SelectionChangedCause cause }) {
assert(cause != null);
_layoutText(minWidth: constraints.minWidth, maxWidth: constraints.maxWidth);
assert(_lastTapDownPosition != null);
if (onSelectionChanged == null) {
return;
}
- final TextPosition position = _textPainter.getPositionForOffset(globalToLocal(_lastTapDownPosition - _paintOffset));
+ final TextPosition position = _textPainter.getPositionForOffset(globalToLocal(_lastTapDownPosition! - _paintOffset));
final TextRange word = _textPainter.getWordBoundary(position);
if (position.offset - word.start <= 1) {
_handleSelectionChange(
@@ -1922,7 +1922,7 @@
_textLayoutLastMaxWidth = maxWidth;
}
- /*late*/ Rect _caretPrototype;
+ late Rect _caretPrototype;
// TODO(garyq): This is no longer producing the highest-fidelity caret
// heights for Android, especially when non-alphabetic languages
@@ -1996,13 +1996,13 @@
// If the floating cursor is enabled, the text cursor's color is [backgroundCursorColor] while
// the floating cursor's color is _cursorColor;
final Paint paint = Paint()
- ..color = _floatingCursorOn ? backgroundCursorColor : _cursorColor;
+ ..color = (_floatingCursorOn ? backgroundCursorColor : _cursorColor)!;
final Offset caretOffset = _textPainter.getOffsetForCaret(textPosition, _caretPrototype) + effectiveOffset;
Rect caretRect = _caretPrototype.shift(caretOffset);
if (_cursorOffset != null)
- caretRect = caretRect.shift(_cursorOffset);
+ caretRect = caretRect.shift(_cursorOffset!);
- final double caretHeight = _textPainter.getFullHeightForCaret(textPosition, _caretPrototype);
+ final double? caretHeight = _textPainter.getFullHeightForCaret(textPosition, _caretPrototype);
if (caretHeight != null) {
switch (defaultTargetPlatform) {
case TargetPlatform.iOS:
@@ -2038,20 +2038,20 @@
if (cursorRadius == null) {
canvas.drawRect(caretRect, paint);
} else {
- final RRect caretRRect = RRect.fromRectAndRadius(caretRect, cursorRadius);
+ final RRect caretRRect = RRect.fromRectAndRadius(caretRect, cursorRadius!);
canvas.drawRRect(caretRRect, paint);
}
if (caretRect != _lastCaretRect) {
_lastCaretRect = caretRect;
if (onCaretChanged != null)
- onCaretChanged(caretRect);
+ onCaretChanged!(caretRect);
}
}
/// Sets the screen position of the floating cursor and the text position
/// closest to the cursor.
- void setFloatingCursor(FloatingCursorDragState state, Offset boundedOffset, TextPosition lastTextPosition, { double resetLerpValue }) {
+ void setFloatingCursor(FloatingCursorDragState state, Offset boundedOffset, TextPosition lastTextPosition, { double? resetLerpValue }) {
assert(state != null);
assert(boundedOffset != null);
assert(lastTextPosition != null);
@@ -2079,14 +2079,14 @@
assert(_floatingCursorOn);
// We always want the floating cursor to render at full opacity.
- final Paint paint = Paint()..color = _cursorColor.withOpacity(0.75);
+ final Paint paint = Paint()..color = _cursorColor!.withOpacity(0.75);
- double/*!*/ sizeAdjustmentX = _kFloatingCaretSizeIncrease.dx;
- double/*!*/ sizeAdjustmentY = _kFloatingCaretSizeIncrease.dy;
+ double sizeAdjustmentX = _kFloatingCaretSizeIncrease.dx;
+ double sizeAdjustmentY = _kFloatingCaretSizeIncrease.dy;
if (_resetFloatingCursorAnimationValue != null) {
- sizeAdjustmentX = ui.lerpDouble(sizeAdjustmentX, 0, _resetFloatingCursorAnimationValue);
- sizeAdjustmentY = ui.lerpDouble(sizeAdjustmentY, 0, _resetFloatingCursorAnimationValue);
+ sizeAdjustmentX = ui.lerpDouble(sizeAdjustmentX, 0, _resetFloatingCursorAnimationValue!)!;
+ sizeAdjustmentY = ui.lerpDouble(sizeAdjustmentY, 0, _resetFloatingCursorAnimationValue!)!;
}
final Rect floatingCaretPrototype = Rect.fromLTRB(
@@ -2106,12 +2106,12 @@
// dragged the floating cursor offscreen. This value is used to account for the
// difference in the rendering position and the raw offset value.
Offset _relativeOrigin = const Offset(0, 0);
- Offset _previousOffset;
+ Offset? _previousOffset;
bool _resetOriginOnLeft = false;
bool _resetOriginOnRight = false;
bool _resetOriginOnTop = false;
bool _resetOriginOnBottom = false;
- double _resetFloatingCursorAnimationValue;
+ double? _resetFloatingCursorAnimationValue;
/// Returns the position within the text field closest to the raw cursor offset.
Offset calculateBoundedFloatingCursorOffset(Offset rawCursorOffset) {
@@ -2122,7 +2122,7 @@
final double rightBound = _textPainter.width + floatingCursorAddedMargin.right;
if (_previousOffset != null)
- deltaPosition = rawCursorOffset - _previousOffset;
+ deltaPosition = rawCursorOffset - _previousOffset!;
// If the raw cursor offset has gone off an edge, we want to reset the relative
// origin of the dragging when the user drags back into the field.
@@ -2166,8 +2166,8 @@
_textLayoutLastMinWidth == constraints.minWidth,
'Last width ($_textLayoutLastMinWidth, $_textLayoutLastMaxWidth) not the same as max width constraint (${constraints.minWidth}, ${constraints.maxWidth}).');
assert(_selectionRects != null);
- final Paint paint = Paint()..color = _selectionColor;
- for (final ui.TextBox box in _selectionRects)
+ final Paint paint = Paint()..color = _selectionColor!;
+ for (final ui.TextBox box in _selectionRects!)
canvas.drawRect(box.toRect().shift(effectiveOffset), paint);
}
@@ -2179,8 +2179,8 @@
final List<TextBox> boxes = _textPainter.getBoxesForSelection(
TextSelection(
- baseOffset: _promptRectRange.start,
- extentOffset: _promptRectRange.end,
+ baseOffset: _promptRectRange!.start,
+ extentOffset: _promptRectRange!.end,
),
);
@@ -2199,16 +2199,16 @@
bool showCaret = false;
if (selection != null && !_floatingCursorOn) {
- if (selection.isCollapsed && _showCursor.value && cursorColor != null)
+ if (selection!.isCollapsed && _showCursor.value && cursorColor != null)
showCaret = true;
- else if (!selection.isCollapsed && _selectionColor != null)
+ else if (!selection!.isCollapsed && _selectionColor != null)
showSelection = true;
_updateSelectionExtentsVisibility(effectiveOffset);
}
if (showSelection) {
assert(selection != null);
- _selectionRects ??= _textPainter.getBoxesForSelection(selection, boxHeightStyle: _selectionHeightStyle, boxWidthStyle: _selectionWidthStyle);
+ _selectionRects ??= _textPainter.getBoxesForSelection(selection!, boxHeightStyle: _selectionHeightStyle, boxWidthStyle: _selectionWidthStyle);
_paintSelection(context.canvas, effectiveOffset);
}
@@ -2221,7 +2221,7 @@
if (showCaret) {
assert(selection != null);
- _paintCaret(context.canvas, effectiveOffset, selection.extent);
+ _paintCaret(context.canvas, effectiveOffset, selection!.extent);
}
if (!paintCursorAboveText)
@@ -2237,8 +2237,8 @@
void _paintHandleLayers(PaintingContext context, List<TextSelectionPoint> endpoints) {
Offset startPoint = endpoints[0].point;
startPoint = Offset(
- startPoint.dx.clamp(0.0, size.width) as double,
- startPoint.dy.clamp(0.0, size.height) as double,
+ startPoint.dx.clamp(0.0, size.width),
+ startPoint.dy.clamp(0.0, size.height),
);
context.pushLayer(
LeaderLayer(link: startHandleLayerLink, offset: startPoint),
@@ -2248,8 +2248,8 @@
if (endpoints.length == 2) {
Offset endPoint = endpoints[1].point;
endPoint = Offset(
- endPoint.dx.clamp(0.0, size.width) as double,
- endPoint.dy.clamp(0.0, size.height) as double,
+ endPoint.dx.clamp(0.0, size.width),
+ endPoint.dy.clamp(0.0, size.height),
);
context.pushLayer(
LeaderLayer(link: endHandleLayerLink, offset: endPoint),
@@ -2265,11 +2265,11 @@
context.pushClipRect(needsCompositing, offset, Offset.zero & size, _paintContents, clipBehavior: clipBehavior);
else
_paintContents(context, offset);
- _paintHandleLayers(context, getEndpointsForSelection(selection));
+ _paintHandleLayers(context, getEndpointsForSelection(selection!));
}
@override
- Rect describeApproximatePaintClip(RenderObject child) => _hasVisualOverflow ? Offset.zero & size : null;
+ Rect? describeApproximatePaintClip(RenderObject child) => _hasVisualOverflow ? Offset.zero & size : null;
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
@@ -2290,7 +2290,7 @@
List<DiagnosticsNode> debugDescribeChildren() {
return <DiagnosticsNode>[
if (text != null)
- text.toDiagnosticsNode(
+ text!.toDiagnosticsNode(
name: 'text',
style: DiagnosticsTreeStyle.transition,
),
diff --git a/packages/flutter/lib/src/rendering/error.dart b/packages/flutter/lib/src/rendering/error.dart
index 1162f58..39e3358 100644
--- a/packages/flutter/lib/src/rendering/error.dart
+++ b/packages/flutter/lib/src/rendering/error.dart
@@ -2,8 +2,6 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-// @dart = 2.8
-
import 'dart:ui' as ui show Paragraph, ParagraphBuilder, ParagraphConstraints, ParagraphStyle, TextStyle;
import 'box.dart';
@@ -59,7 +57,7 @@
final String message;
// TODO(ianh): should be final
- /*late*/ ui.Paragraph/*?*/ _paragraph;
+ ui.Paragraph? _paragraph;
@override
double computeMaxIntrinsicWidth(double height) {
@@ -158,11 +156,11 @@
width -= padding.left + padding.right;
left += padding.left;
}
- _paragraph.layout(ui.ParagraphConstraints(width: width));
- if (size.height > padding.top + _paragraph.height + padding.bottom) {
+ _paragraph!.layout(ui.ParagraphConstraints(width: width));
+ if (size.height > padding.top + _paragraph!.height + padding.bottom) {
top += padding.top;
}
- context.canvas.drawParagraph(_paragraph, offset + Offset(left, top));
+ context.canvas.drawParagraph(_paragraph!, offset + Offset(left, top));
}
} catch (e) {
// Intentionally left empty.
diff --git a/packages/flutter/lib/src/rendering/flex.dart b/packages/flutter/lib/src/rendering/flex.dart
index 9b6330d..97ce134 100644
--- a/packages/flutter/lib/src/rendering/flex.dart
+++ b/packages/flutter/lib/src/rendering/flex.dart
@@ -2,8 +2,6 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-// @dart = 2.8
-
import 'dart:math' as math;
import 'package:flutter/foundation.dart';
@@ -41,7 +39,7 @@
/// non-zero, the amount of space the child's can occupy in the main axis is
/// determined by dividing the free space (after placing the inflexible
/// children) according to the flex factors of the flexible children.
- int flex;
+ int? flex;
/// How a flexible child is inscribed into the available space.
///
@@ -50,7 +48,7 @@
/// [FlexFit.tight], the child is required to fill the available space. If the
/// fit is [FlexFit.loose], the child can be at most as large as the available
/// space (but is allowed to be smaller).
- FlexFit fit;
+ FlexFit? fit;
@override
String toString() => '${super.toString()}; flex=$flex; fit=$fit';
@@ -198,7 +196,7 @@
baseline,
}
-bool/*?*/ _startIsTopLeft(Axis direction, TextDirection textDirection, VerticalDirection verticalDirection) {
+bool? _startIsTopLeft(Axis direction, TextDirection? textDirection, VerticalDirection? verticalDirection) {
assert(direction != null);
// If the relevant value of textDirection or verticalDirection is null, this returns null too.
switch (direction) {
@@ -208,18 +206,19 @@
return true;
case TextDirection.rtl:
return false;
+ case null:
+ return null;
}
- break;
case Axis.vertical:
switch (verticalDirection) {
case VerticalDirection.down:
return true;
case VerticalDirection.up:
return false;
+ case null:
+ return null;
}
- break;
}
- return null;
}
typedef _ChildSizingFunction = double Function(RenderBox child, double extent);
@@ -279,14 +278,14 @@
/// By default, the flex layout is horizontal and children are aligned to the
/// start of the main axis and the center of the cross axis.
RenderFlex({
- List<RenderBox> children,
+ List<RenderBox>? children,
Axis direction = Axis.horizontal,
MainAxisSize mainAxisSize = MainAxisSize.max,
MainAxisAlignment mainAxisAlignment = MainAxisAlignment.start,
CrossAxisAlignment crossAxisAlignment = CrossAxisAlignment.center,
- TextDirection textDirection,
+ TextDirection? textDirection,
VerticalDirection verticalDirection = VerticalDirection.down,
- TextBaseline textBaseline,
+ TextBaseline? textBaseline,
Clip clipBehavior = Clip.none,
}) : assert(direction != null),
assert(mainAxisAlignment != null),
@@ -393,9 +392,9 @@
/// If the [direction] is [Axis.vertical], and the [crossAxisAlignment] is
/// either [CrossAxisAlignment.start] or [CrossAxisAlignment.end], then the
/// [textDirection] must not be null.
- TextDirection get textDirection => _textDirection;
- TextDirection _textDirection;
- set textDirection(TextDirection value) {
+ TextDirection? get textDirection => _textDirection;
+ TextDirection? _textDirection;
+ set textDirection(TextDirection? value) {
if (_textDirection != value) {
_textDirection = value;
markNeedsLayout();
@@ -432,9 +431,9 @@
/// If aligning items according to their baseline, which baseline to use.
///
/// Must not be null if [crossAxisAlignment] is [CrossAxisAlignment.baseline].
- TextBaseline get textBaseline => _textBaseline;
- TextBaseline _textBaseline;
- set textBaseline(TextBaseline value) {
+ TextBaseline? get textBaseline => _textBaseline;
+ TextBaseline? _textBaseline;
+ set textBaseline(TextBaseline? value) {
assert(_crossAxisAlignment != CrossAxisAlignment.baseline || value != null);
if (_textBaseline != value) {
_textBaseline = value;
@@ -482,10 +481,10 @@
}
// Set during layout if overflow occurred on the main axis.
- double _overflow;
+ double? _overflow;
// Check whether any meaningful overflow is present. Values below an epsilon
// are treated as not overflowing.
- bool get _hasOverflow => _overflow > precisionErrorTolerance;
+ bool get _hasOverflow => _overflow! > precisionErrorTolerance;
/// {@macro flutter.widgets.Clip}
///
@@ -508,9 +507,9 @@
}
double _getIntrinsicSize({
- @required Axis sizingDirection,
- @required double extent, // the extent in the direction that isn't the sizing direction
- @required _ChildSizingFunction childSize, // a method to find the size in the sizing direction
+ required Axis sizingDirection,
+ required double extent, // the extent in the direction that isn't the sizing direction
+ required _ChildSizingFunction childSize, // a method to find the size in the sizing direction
}) {
if (_direction == sizingDirection) {
// INTRINSIC MAIN SIZE
@@ -519,7 +518,7 @@
double totalFlex = 0.0;
double inflexibleSpace = 0.0;
double maxFlexFractionSoFar = 0.0;
- RenderBox child = firstChild;
+ RenderBox? child = firstChild;
while (child != null) {
final int flex = _getFlex(child);
totalFlex += flex;
@@ -544,13 +543,12 @@
int totalFlex = 0;
double inflexibleSpace = 0.0;
double maxCrossSize = 0.0;
- RenderBox child = firstChild;
+ RenderBox? child = firstChild;
while (child != null) {
final int flex = _getFlex(child);
totalFlex += flex;
- // TODO(ianh): these should be late final
- /*late*/ double/*!*/ mainSize;
- /*late*/ double/*!*/ crossSize;
+ late final double mainSize;
+ late final double crossSize;
if (flex == 0) {
switch (_direction) {
case Axis.horizontal:
@@ -625,7 +623,7 @@
}
@override
- double computeDistanceToActualBaseline(TextBaseline baseline) {
+ double? computeDistanceToActualBaseline(TextBaseline baseline) {
if (_direction == Axis.horizontal)
return defaultComputeDistanceToHighestActualBaseline(baseline);
return defaultComputeDistanceToFirstActualBaseline(baseline);
@@ -648,7 +646,6 @@
case Axis.vertical:
return child.size.width;
}
- return null;
}
double _getMainSize(RenderBox child) {
@@ -658,7 +655,6 @@
case Axis.vertical:
return child.size.height;
}
- return null;
}
@override
@@ -675,8 +671,8 @@
double crossSize = 0.0;
double allocatedSize = 0.0; // Sum of the sizes of the non-flexible children.
- RenderBox child = firstChild;
- RenderBox lastFlexChild;
+ RenderBox? child = firstChild;
+ RenderBox? lastFlexChild;
while (child != null) {
final FlexParentData childParentData = child.parentData as FlexParentData;
totalChildren++;
@@ -688,7 +684,7 @@
final String dimension = _direction == Axis.horizontal ? 'width' : 'height';
DiagnosticsNode error, message;
final List<DiagnosticsNode> addendum = <DiagnosticsNode>[];
- if (!canFlex && (mainAxisSize == MainAxisSize.max || _getFit(child) == FlexFit.tight)) {
+ if (!canFlex && (mainAxisSize == MainAxisSize.max || _getFit(child!) == FlexFit.tight)) {
error = ErrorSummary('RenderFlex children have non-zero flex but incoming $dimension constraints are unbounded.');
message = ErrorDescription(
'When a $identity is in a parent that does not provide a finite $dimension constraint, for example '
@@ -696,16 +692,16 @@
'axis. Setting a flex on a child (e.g. using Expanded) indicates that the child is to '
'expand to fill the remaining space in the $axis direction.'
);
- RenderBox node = this;
+ RenderBox? node = this;
switch (_direction) {
case Axis.horizontal:
- while (!node.constraints.hasBoundedWidth && node.parent is RenderBox)
+ while (!node!.constraints.hasBoundedWidth && node.parent is RenderBox)
node = node.parent as RenderBox;
if (!node.constraints.hasBoundedWidth)
node = null;
break;
case Axis.vertical:
- while (!node.constraints.hasBoundedHeight && node.parent is RenderBox)
+ while (!node!.constraints.hasBoundedHeight && node.parent is RenderBox)
node = node.parent as RenderBox;
if (!node.constraints.hasBoundedHeight)
node = null;
@@ -746,7 +742,7 @@
),
]);
}());
- totalFlex += childParentData.flex;
+ totalFlex += flex;
lastFlexChild = child;
} else {
BoxConstraints innerConstraints;
@@ -790,8 +786,7 @@
final int flex = _getFlex(child);
if (flex > 0) {
final double maxChildExtent = canFlex ? (child == lastFlexChild ? (freeSpace - allocatedFlexSpace) : spacePerFlex * flex) : double.infinity;
- // TODO(ianh): this should be late final
- /*late*/ double/*!*/ minChildExtent;
+ late final double minChildExtent;
switch (_getFit(child)) {
case FlexFit.tight:
assert(maxChildExtent < double.infinity);
@@ -845,7 +840,7 @@
throw FlutterError('To use FlexAlignItems.baseline, you must also specify which baseline to use using the "baseline" argument.');
return true;
}());
- final double distance = child.getDistanceToBaseline(textBaseline, onlyReal: true);
+ final double? distance = child.getDistanceToBaseline(textBaseline!, onlyReal: true);
if (distance != null) {
maxBaselineDistance = math.max(maxBaselineDistance, distance);
maxSizeAboveBaseline = math.max(
@@ -882,9 +877,8 @@
final double actualSizeDelta = actualSize - allocatedSize;
_overflow = math.max(0.0, -actualSizeDelta);
final double remainingSpace = math.max(0.0, actualSizeDelta);
- // TODO(ianh): these should be late final
- /*late*/ double/*!*/ leadingSpace;
- /*late*/ double/*!*/ betweenSpace;
+ late final double leadingSpace;
+ late final double betweenSpace;
// flipMainAxis is used to decide whether to lay out left-to-right/top-to-bottom (false), or
// right-to-left/bottom-to-top (true). The _startIsTopLeft will return null if there's only
// one child and the relevant direction is null, in which case we arbitrarily decide not to
@@ -941,7 +935,7 @@
childCrossPosition = 0.0;
if (_direction == Axis.horizontal) {
assert(textBaseline != null);
- final double distance = child.getDistanceToBaseline(textBaseline, onlyReal: true);
+ final double? distance = child.getDistanceToBaseline(textBaseline!, onlyReal: true);
if (distance != null)
childCrossPosition = maxBaselineDistance - distance;
}
@@ -967,7 +961,7 @@
}
@override
- bool hitTestChildren(BoxHitTestResult result, { Offset position }) {
+ bool hitTestChildren(BoxHitTestResult result, { required Offset position }) {
return defaultHitTestChildren(result, position: position);
}
@@ -1021,10 +1015,10 @@
Rect overflowChildRect;
switch (_direction) {
case Axis.horizontal:
- overflowChildRect = Rect.fromLTWH(0.0, 0.0, size.width + _overflow, 0.0);
+ overflowChildRect = Rect.fromLTWH(0.0, 0.0, size.width + _overflow!, 0.0);
break;
case Axis.vertical:
- overflowChildRect = Rect.fromLTWH(0.0, 0.0, 0.0, size.height + _overflow);
+ overflowChildRect = Rect.fromLTWH(0.0, 0.0, 0.0, size.height + _overflow!);
break;
}
paintOverflowIndicator(context, offset, Offset.zero & size, overflowChildRect, overflowHints: debugOverflowHints);
@@ -1033,12 +1027,12 @@
}
@override
- Rect describeApproximatePaintClip(RenderObject child) => _hasOverflow ? Offset.zero & size : null;
+ Rect? describeApproximatePaintClip(RenderObject child) => _hasOverflow ? Offset.zero & size : null;
@override
String toStringShort() {
String header = super.toStringShort();
- if (_overflow is double && _hasOverflow)
+ if (_overflow != null && _hasOverflow)
header += ' OVERFLOWING';
return header;
}
diff --git a/packages/flutter/lib/src/rendering/flow.dart b/packages/flutter/lib/src/rendering/flow.dart
index 49ab2ba..2cc8dd9 100644
--- a/packages/flutter/lib/src/rendering/flow.dart
+++ b/packages/flutter/lib/src/rendering/flow.dart
@@ -2,8 +2,6 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-// @dart = 2.8
-
import 'dart:ui' as ui show Color;
import 'package:flutter/foundation.dart';
@@ -32,7 +30,7 @@
/// The size of the [i]th child.
///
/// If [i] is negative or exceeds [childCount], returns null.
- Size getChildSize(int i);
+ Size? getChildSize(int i);
/// Paint the [i]th child using the given transform.
///
@@ -59,9 +57,9 @@
/// * [RenderFlow]
abstract class FlowDelegate {
/// The flow will repaint whenever [repaint] notifies its listeners.
- const FlowDelegate({ Listenable repaint }) : _repaint = repaint;
+ const FlowDelegate({ Listenable? repaint }) : _repaint = repaint;
- final Listenable _repaint;
+ final Listenable? _repaint;
/// Override to control the size of the container for the children.
///
@@ -145,7 +143,7 @@
/// matrix, use the [FlowPaintingContext.paintChild] function from an override
/// of the [FlowDelegate.paintChildren] function.
class FlowParentData extends ContainerBoxParentData<RenderBox> {
- Matrix4 _transform;
+ Matrix4? _transform;
}
/// Implements the flow layout algorithm.
@@ -181,8 +179,8 @@
/// For optimal performance, consider using children that return true from
/// [isRepaintBoundary].
RenderFlow({
- List<RenderBox> children,
- @required FlowDelegate delegate,
+ List<RenderBox>? children,
+ required FlowDelegate delegate,
}) : assert(delegate != null),
_delegate = delegate {
addAll(children);
@@ -190,7 +188,7 @@
@override
void setupParentData(RenderBox child) {
- final ParentData childParentData = child.parentData;
+ final ParentData? childParentData = child.parentData;
if (childParentData is FlowParentData)
childParentData._transform = null;
else
@@ -285,7 +283,7 @@
size = _getSize(constraints);
int i = 0;
_randomAccessChildren.clear();
- RenderBox child = firstChild;
+ RenderBox? child = firstChild;
while (child != null) {
_randomAccessChildren.add(child);
final BoxConstraints innerConstraints = _delegate.getConstraintsForChild(i, constraints);
@@ -304,18 +302,18 @@
final List<int> _lastPaintOrder = <int>[];
// Only valid during paint.
- PaintingContext _paintingContext;
- Offset _paintingOffset;
+ PaintingContext? _paintingContext;
+ Offset? _paintingOffset;
@override
- Size getChildSize(int i) {
+ Size? getChildSize(int i) {
if (i < 0 || i >= _randomAccessChildren.length)
return null;
return _randomAccessChildren[i].size;
}
@override
- void paintChild(int i, { Matrix4 transform, double opacity = 1.0 }) {
+ void paintChild(int i, { Matrix4? transform, double opacity = 1.0 }) {
transform ??= Matrix4.identity();
final RenderBox child = _randomAccessChildren[i];
final FlowParentData childParentData = child.parentData as FlowParentData;
@@ -341,10 +339,10 @@
context.paintChild(child, offset);
}
if (opacity == 1.0) {
- _paintingContext.pushTransform(needsCompositing, _paintingOffset, transform, painter);
+ _paintingContext!.pushTransform(needsCompositing, _paintingOffset!, transform, painter);
} else {
- _paintingContext.pushOpacity(_paintingOffset, ui.Color.getAlphaFromOpacity(opacity), (PaintingContext context, Offset offset) {
- context.pushTransform(needsCompositing, offset, transform, painter);
+ _paintingContext!.pushOpacity(_paintingOffset!, ui.Color.getAlphaFromOpacity(opacity), (PaintingContext context, Offset offset) {
+ context.pushTransform(needsCompositing, offset, transform!, painter);
});
}
}
@@ -371,7 +369,7 @@
}
@override
- bool hitTestChildren(BoxHitTestResult result, { Offset position }) {
+ bool hitTestChildren(BoxHitTestResult result, { required Offset position }) {
final List<RenderBox> children = getChildrenAsList();
for (int i = _lastPaintOrder.length - 1; i >= 0; --i) {
final int childIndex = _lastPaintOrder[i];
@@ -379,14 +377,14 @@
continue;
final RenderBox child = children[childIndex];
final FlowParentData childParentData = child.parentData as FlowParentData;
- final Matrix4 transform = childParentData._transform;
+ final Matrix4? transform = childParentData._transform;
if (transform == null)
continue;
final bool absorbed = result.addWithPaintTransform(
transform: transform,
position: position,
- hitTest: (BoxHitTestResult result, Offset position) {
- return child.hitTest(result, position: position);
+ hitTest: (BoxHitTestResult result, Offset? position) {
+ return child.hitTest(result, position: position!);
},
);
if (absorbed)
@@ -399,7 +397,7 @@
void applyPaintTransform(RenderBox child, Matrix4 transform) {
final FlowParentData childParentData = child.parentData as FlowParentData;
if (childParentData._transform != null)
- transform.multiply(childParentData._transform);
+ transform.multiply(childParentData._transform!);
super.applyPaintTransform(child, transform);
}
}
diff --git a/packages/flutter/lib/src/rendering/image.dart b/packages/flutter/lib/src/rendering/image.dart
index 1f36519..2659f69 100644
--- a/packages/flutter/lib/src/rendering/image.dart
+++ b/packages/flutter/lib/src/rendering/image.dart
@@ -2,8 +2,6 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-// @dart = 2.8
-
import 'dart:ui' as ui show Image;
import 'box.dart';
@@ -27,19 +25,19 @@
/// must not be null. The [textDirection] argument must not be null if
/// [alignment] will need resolving or if [matchTextDirection] is true.
RenderImage({
- ui.Image image,
+ ui.Image? image,
this.debugImageLabel,
- double width,
- double height,
+ double? width,
+ double? height,
double scale = 1.0,
- Color color,
- BlendMode colorBlendMode,
- BoxFit fit,
+ Color? color,
+ BlendMode? colorBlendMode,
+ BoxFit? fit,
AlignmentGeometry alignment = Alignment.center,
ImageRepeat repeat = ImageRepeat.noRepeat,
- Rect centerSlice,
+ Rect? centerSlice,
bool matchTextDirection = false,
- TextDirection textDirection,
+ TextDirection? textDirection,
bool invertColors = false,
bool isAntiAlias = false,
FilterQuality filterQuality = FilterQuality.low,
@@ -67,8 +65,8 @@
_updateColorFilter();
}
- Alignment _resolvedAlignment;
- bool _flipHorizontally;
+ Alignment? _resolvedAlignment;
+ bool? _flipHorizontally;
void _resolve() {
if (_resolvedAlignment != null)
@@ -84,9 +82,9 @@
}
/// The image to display.
- ui.Image get image => _image;
- ui.Image _image;
- set image(ui.Image value) {
+ ui.Image? get image => _image;
+ ui.Image? _image;
+ set image(ui.Image? value) {
if (value == _image)
return;
_image = value;
@@ -96,15 +94,15 @@
}
/// A string used to identify the source of the image.
- String debugImageLabel;
+ String? debugImageLabel;
/// If non-null, requires the image to have this width.
///
/// If null, the image will pick a size that best preserves its intrinsic
/// aspect ratio.
- double get width => _width;
- double _width;
- set width(double value) {
+ double? get width => _width;
+ double? _width;
+ set width(double? value) {
if (value == _width)
return;
_width = value;
@@ -115,9 +113,9 @@
///
/// If null, the image will pick a size that best preserves its intrinsic
/// aspect ratio.
- double get height => _height;
- double _height;
- set height(double value) {
+ double? get height => _height;
+ double? _height;
+ set height(double? value) {
if (value == _height)
return;
_height = value;
@@ -137,19 +135,19 @@
markNeedsLayout();
}
- ColorFilter _colorFilter;
+ ColorFilter? _colorFilter;
void _updateColorFilter() {
if (_color == null)
_colorFilter = null;
else
- _colorFilter = ColorFilter.mode(_color, _colorBlendMode ?? BlendMode.srcIn);
+ _colorFilter = ColorFilter.mode(_color!, _colorBlendMode ?? BlendMode.srcIn);
}
/// If non-null, this color is blended with each image pixel using [colorBlendMode].
- Color get color => _color;
- Color _color;
- set color(Color value) {
+ Color? get color => _color;
+ Color? _color;
+ set color(Color? value) {
if (value == _color)
return;
_color = value;
@@ -180,9 +178,9 @@
/// See also:
///
/// * [BlendMode], which includes an illustration of the effect of each blend mode.
- BlendMode get colorBlendMode => _colorBlendMode;
- BlendMode _colorBlendMode;
- set colorBlendMode(BlendMode value) {
+ BlendMode? get colorBlendMode => _colorBlendMode;
+ BlendMode? _colorBlendMode;
+ set colorBlendMode(BlendMode? value) {
if (value == _colorBlendMode)
return;
_colorBlendMode = value;
@@ -194,9 +192,9 @@
///
/// The default varies based on the other fields. See the discussion at
/// [paintImage].
- BoxFit get fit => _fit;
- BoxFit _fit;
- set fit(BoxFit value) {
+ BoxFit? get fit => _fit;
+ BoxFit? _fit;
+ set fit(BoxFit? value) {
if (value == _fit)
return;
_fit = value;
@@ -235,9 +233,9 @@
/// region of the image above and below the center slice will be stretched
/// only horizontally and the region of the image to the left and right of
/// the center slice will be stretched only vertically.
- Rect get centerSlice => _centerSlice;
- Rect _centerSlice;
- set centerSlice(Rect value) {
+ Rect? get centerSlice => _centerSlice;
+ Rect? _centerSlice;
+ set centerSlice(Rect? value) {
if (value == _centerSlice)
return;
_centerSlice = value;
@@ -287,9 +285,9 @@
/// This may be changed to null, but only after the [alignment] and
/// [matchTextDirection] properties have been changed to values that do not
/// depend on the direction.
- TextDirection get textDirection => _textDirection;
- TextDirection _textDirection;
- set textDirection(TextDirection value) {
+ TextDirection? get textDirection => _textDirection;
+ TextDirection? _textDirection;
+ set textDirection(TextDirection? value) {
if (_textDirection == value)
return;
_textDirection = value;
@@ -329,8 +327,8 @@
return constraints.smallest;
return constraints.constrainSizeAndAttemptToPreserveAspectRatio(Size(
- _image.width.toDouble() / _scale,
- _image.height.toDouble() / _scale,
+ _image!.width.toDouble() / _scale,
+ _image!.height.toDouble() / _scale,
));
}
@@ -380,15 +378,15 @@
paintImage(
canvas: context.canvas,
rect: offset & size,
- image: _image,
+ image: _image!,
debugImageLabel: debugImageLabel,
scale: _scale,
colorFilter: _colorFilter,
fit: _fit,
- alignment: _resolvedAlignment,
+ alignment: _resolvedAlignment!,
centerSlice: _centerSlice,
repeat: _repeat,
- flipHorizontally: _flipHorizontally,
+ flipHorizontally: _flipHorizontally!,
invertColors: invertColors,
filterQuality: _filterQuality,
isAntiAlias: _isAntiAlias,
diff --git a/packages/flutter/lib/src/rendering/layer.dart b/packages/flutter/lib/src/rendering/layer.dart
index 3a45a79..83d789b 100644
--- a/packages/flutter/lib/src/rendering/layer.dart
+++ b/packages/flutter/lib/src/rendering/layer.dart
@@ -2,8 +2,6 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-// @dart = 2.8
-
import 'dart:async';
import 'dart:collection';
import 'dart:ui' as ui;
@@ -25,8 +23,8 @@
/// Create an entry of found annotation by providing the object and related
/// information.
const AnnotationEntry({
- @required this.annotation,
- @required this.localPosition,
+ required this.annotation,
+ required this.localPosition,
}) : assert(localPosition != null);
/// The annotation object that is found.
@@ -104,7 +102,7 @@
/// Only subclasses of [ContainerLayer] can have children in the layer tree.
/// All other layer classes are used for leaves in the layer tree.
@override
- ContainerLayer get parent => super.parent as ContainerLayer;
+ ContainerLayer? get parent => super.parent as ContainerLayer?;
// Whether this layer has any changes since its last call to [addToScene].
//
@@ -168,8 +166,8 @@
/// This is for debug and test purpose only. It only becomes valid after
/// calling [updateSubtreeNeedsAddToScene].
@visibleForTesting
- bool get debugSubtreeNeedsAddToScene {
- bool result;
+ bool? get debugSubtreeNeedsAddToScene {
+ bool? result;
assert(() {
result = _needsAddToScene;
return true;
@@ -191,7 +189,7 @@
/// layer. The web engine could, for example, update the properties of
/// previously rendered HTML DOM nodes rather than creating new nodes.
@protected
- ui.EngineLayer get engineLayer => _engineLayer;
+ ui.EngineLayer? get engineLayer => _engineLayer;
/// Sets the engine layer used to render this layer.
///
@@ -199,7 +197,7 @@
/// in turn returns the engine layer produced by one of [ui.SceneBuilder]'s
/// "push" methods, such as [ui.SceneBuilder.pushOpacity].
@protected
- set engineLayer(ui.EngineLayer value) {
+ set engineLayer(ui.EngineLayer? value) {
_engineLayer = value;
if (!alwaysNeedsAddToScene) {
// The parent must construct a new engine layer to add this layer to, and
@@ -222,12 +220,12 @@
// `addToScene`, but the parent does not clear the flag until some future
// frame decides to render it, at which point the parent knows that it
// cannot retain its engine layer and will call `addToScene` again.
- if (parent != null && !parent.alwaysNeedsAddToScene) {
- parent.markNeedsAddToScene();
+ if (parent != null && !parent!.alwaysNeedsAddToScene) {
+ parent!.markNeedsAddToScene();
}
}
}
- ui.EngineLayer _engineLayer;
+ ui.EngineLayer? _engineLayer;
/// Traverses the layer subtree starting from this layer and determines whether it needs [addToScene].
///
@@ -245,12 +243,12 @@
}
/// This layer's next sibling in the parent layer's child list.
- Layer get nextSibling => _nextSibling;
- Layer _nextSibling;
+ Layer? get nextSibling => _nextSibling;
+ Layer? _nextSibling;
/// This layer's previous sibling in the parent layer's child list.
- Layer get previousSibling => _previousSibling;
- Layer _previousSibling;
+ Layer? get previousSibling => _previousSibling;
+ Layer? _previousSibling;
@override
void dropChild(AbstractNode child) {
@@ -327,10 +325,10 @@
/// by their children, hence making all of its ancestors opaque to this type
/// of annotation.
@protected
- bool findAnnotations<S>(
+ bool findAnnotations<S extends Object>(
AnnotationResult<S> result,
Offset localPosition, {
- @required bool onlyFirst,
+ required bool onlyFirst,
}) {
return false;
}
@@ -355,7 +353,7 @@
/// * [findAllAnnotations], which is similar but returns all annotations found
/// at the given position.
/// * [AnnotatedRegionLayer], for placing values in the layer tree.
- S find<S>(Offset localPosition) {
+ S? find<S extends Object>(Offset localPosition) {
final AnnotationResult<S> result = AnnotationResult<S>();
findAnnotations<S>(result, localPosition, onlyFirst: true);
return result.entries.isEmpty ? null : result.entries.first.annotation;
@@ -389,7 +387,7 @@
'Use findAllAnnotations(...).annotations instead. '
'This feature was deprecated after v1.10.14.'
)
- Iterable<S> findAll<S>(Offset localPosition) {
+ Iterable<S> findAll<S extends Object>(Offset localPosition) {
final AnnotationResult<S> result = findAllAnnotations(localPosition);
return result.entries.map((AnnotationEntry<S> entry) => entry.annotation);
}
@@ -414,7 +412,7 @@
/// * [find], which is similar but returns the first annotation found at the
/// given position.
/// * [AnnotatedRegionLayer], for placing values in the layer tree.
- AnnotationResult<S> findAllAnnotations<S>(Offset localPosition) {
+ AnnotationResult<S> findAllAnnotations<S extends Object>(Offset localPosition) {
final AnnotationResult<S> result = AnnotationResult<S>();
findAnnotations<S>(result, localPosition, onlyFirst: false);
return result;
@@ -438,7 +436,7 @@
// changed so A's _needsAddToScene is true. This contradicts
// _needsAddToScene being false.
if (!_needsAddToScene && _engineLayer != null) {
- builder.addRetained(_engineLayer);
+ builder.addRetained(_engineLayer!);
return;
}
addToScene(builder);
@@ -487,9 +485,9 @@
///
/// The scene must be explicitly recomposited after this property is changed
/// (as described at [Layer]).
- ui.Picture get picture => _picture;
- ui.Picture _picture;
- set picture(ui.Picture picture) {
+ ui.Picture? get picture => _picture;
+ ui.Picture? _picture;
+ set picture(ui.Picture? picture) {
markNeedsAddToScene();
_picture = picture;
}
@@ -532,7 +530,7 @@
@override
void addToScene(ui.SceneBuilder builder, [ Offset layerOffset = Offset.zero ]) {
assert(picture != null);
- builder.addPicture(layerOffset, picture, isComplexHint: isComplexHint, willChangeHint: willChangeHint);
+ builder.addPicture(layerOffset, picture!, isComplexHint: isComplexHint, willChangeHint: willChangeHint);
}
@override
@@ -547,8 +545,7 @@
}
@override
- @protected
- bool findAnnotations<S>(AnnotationResult<S> result, Offset localPosition, { @required bool onlyFirst }) {
+ bool findAnnotations<S extends Object>(AnnotationResult<S> result, Offset localPosition, { required bool onlyFirst }) {
return false;
}
}
@@ -584,8 +581,8 @@
/// identified by [textureId], if [freeze] is true new texture frames will not be
/// populated to the texture, and use [filterQuality] to set layer's [FilterQuality].
TextureLayer({
- @required this.rect,
- @required this.textureId,
+ required this.rect,
+ required this.textureId,
this.freeze = false,
this.filterQuality = ui.FilterQuality.low,
}) : assert(rect != null),
@@ -623,8 +620,7 @@
}
@override
- @protected
- bool findAnnotations<S>(AnnotationResult<S> result, Offset localPosition, { @required bool onlyFirst }) {
+ bool findAnnotations<S extends Object>(AnnotationResult<S> result, Offset localPosition, { required bool onlyFirst }) {
return false;
}
}
@@ -636,8 +632,8 @@
///
/// The `rect` and `viewId` parameters must not be null.
PlatformViewLayer({
- @required this.rect,
- @required this.viewId,
+ required this.rect,
+ required this.viewId,
}) : assert(rect != null),
assert(viewId != null);
@@ -668,11 +664,11 @@
class PerformanceOverlayLayer extends Layer {
/// Creates a layer that displays a performance overlay.
PerformanceOverlayLayer({
- @required Rect overlayRect,
- @required this.optionsMask,
- @required this.rasterizerThreshold,
- @required this.checkerboardRasterCacheImages,
- @required this.checkerboardOffscreenLayers,
+ required Rect overlayRect,
+ required this.optionsMask,
+ required this.rasterizerThreshold,
+ required this.checkerboardRasterCacheImages,
+ required this.checkerboardOffscreenLayers,
}) : _overlayRect = overlayRect;
/// The rectangle in this layer's coordinate system that the overlay should occupy.
@@ -731,8 +727,7 @@
}
@override
- @protected
- bool findAnnotations<S>(AnnotationResult<S> result, Offset localPosition, { @required bool onlyFirst }) {
+ bool findAnnotations<S extends Object>(AnnotationResult<S> result, Offset localPosition, { required bool onlyFirst }) {
return false;
}
}
@@ -744,12 +739,12 @@
/// [ContainerLayer] which apply more elaborate effects in the process.
class ContainerLayer extends Layer {
/// The first composited layer in this layer's child list.
- Layer get firstChild => _firstChild;
- Layer _firstChild;
+ Layer? get firstChild => _firstChild;
+ Layer? _firstChild;
/// The last composited layer in this layer's child list.
- Layer get lastChild => _lastChild;
- Layer _lastChild;
+ Layer? get lastChild => _lastChild;
+ Layer? _lastChild;
/// Returns whether this layer has at least one child layer.
bool get hasChildren => _firstChild != null;
@@ -761,7 +756,7 @@
// both to render the whole layer tree (e.g. a normal application frame) and
// to render a subtree (e.g. `OffsetLayer.toImage`).
ui.Scene buildScene(ui.SceneBuilder builder) {
- List<PictureLayer> temporaryLayers;
+ List<PictureLayer>? temporaryLayers;
assert(() {
if (debugCheckElevationsEnabled) {
temporaryLayers = _debugCheckElevations();
@@ -780,7 +775,7 @@
// PhysicalModelLayers. If we don't, we'll end up adding duplicate layers
// or continuing to render stale outlines.
if (temporaryLayers != null) {
- for (final PictureLayer temporaryLayer in temporaryLayers) {
+ for (final PictureLayer temporaryLayer in temporaryLayers!) {
temporaryLayer.remove();
}
}
@@ -789,21 +784,21 @@
return scene;
}
- bool _debugUltimatePreviousSiblingOf(Layer child, { Layer equals }) {
+ bool _debugUltimatePreviousSiblingOf(Layer child, { Layer? equals }) {
assert(child.attached == attached);
while (child.previousSibling != null) {
assert(child.previousSibling != child);
- child = child.previousSibling;
+ child = child.previousSibling!;
assert(child.attached == attached);
}
return child == equals;
}
- bool _debugUltimateNextSiblingOf(Layer child, { Layer equals }) {
+ bool _debugUltimateNextSiblingOf(Layer child, { Layer? equals }) {
assert(child.attached == attached);
while (child._nextSibling != null) {
assert(child._nextSibling != child);
- child = child._nextSibling;
+ child = child._nextSibling!;
assert(child.attached == attached);
}
return child == equals;
@@ -813,15 +808,15 @@
final ui.PictureRecorder recorder = ui.PictureRecorder();
final Canvas canvas = Canvas(recorder);
canvas.drawPath(
- child.clipPath,
+ child.clipPath!,
Paint()
..color = const Color(0xFFAA0000)
..style = PaintingStyle.stroke
// The elevation may be 0 or otherwise too small to notice.
// Adding 10 to it makes it more visually obvious.
- ..strokeWidth = child.elevation + 10.0,
+ ..strokeWidth = child.elevation! + 10.0,
);
- final PictureLayer pictureLayer = PictureLayer(child.clipPath.getBounds())
+ final PictureLayer pictureLayer = PictureLayer(child.clipPath!.getBounds())
..picture = recorder.endRecording()
..debugCreator = child;
child.append(pictureLayer);
@@ -866,24 +861,24 @@
'debugCheckElevations has either already visited this layer or failed '
'to remove the added picture from it.',
);
- double accumulatedElevation = physicalModelLayer.elevation;
- Layer ancestor = physicalModelLayer.parent;
+ double accumulatedElevation = physicalModelLayer.elevation!;
+ Layer? ancestor = physicalModelLayer.parent;
while (ancestor != null) {
if (ancestor is PhysicalModelLayer) {
- accumulatedElevation += ancestor.elevation;
+ accumulatedElevation += ancestor.elevation!;
}
ancestor = ancestor.parent;
}
for (int j = 0; j <= i; j++) {
final PhysicalModelLayer predecessor = physicalModelLayers[j];
- double predecessorAccumulatedElevation = predecessor.elevation;
+ double predecessorAccumulatedElevation = predecessor.elevation!;
ancestor = predecessor.parent;
while (ancestor != null) {
if (ancestor == predecessor) {
continue;
}
if (ancestor is PhysicalModelLayer) {
- predecessorAccumulatedElevation += ancestor.elevation;
+ predecessorAccumulatedElevation += ancestor.elevation!;
}
ancestor = ancestor.parent;
}
@@ -906,7 +901,7 @@
@override
void updateSubtreeNeedsAddToScene() {
super.updateSubtreeNeedsAddToScene();
- Layer child = firstChild;
+ Layer? child = firstChild;
while (child != null) {
child.updateSubtreeNeedsAddToScene();
_needsAddToScene = _needsAddToScene || child._needsAddToScene;
@@ -915,9 +910,8 @@
}
@override
- @protected
- bool findAnnotations<S>(AnnotationResult<S> result, Offset localPosition, { @required bool onlyFirst }) {
- for (Layer child = lastChild; child != null; child = child.previousSibling) {
+ bool findAnnotations<S extends Object>(AnnotationResult<S> result, Offset localPosition, { required bool onlyFirst }) {
+ for (Layer? child = lastChild; child != null; child = child.previousSibling) {
final bool isAbsorbed = child.findAnnotations<S>(result, localPosition, onlyFirst: onlyFirst);
if (isAbsorbed)
return true;
@@ -930,7 +924,7 @@
@override
void attach(Object owner) {
super.attach(owner);
- Layer child = firstChild;
+ Layer? child = firstChild;
while (child != null) {
child.attach(owner);
child = child.nextSibling;
@@ -940,7 +934,7 @@
@override
void detach() {
super.detach();
- Layer child = firstChild;
+ Layer? child = firstChild;
while (child != null) {
child.detach();
child = child.nextSibling;
@@ -959,14 +953,14 @@
assert(() {
Layer node = this;
while (node.parent != null)
- node = node.parent;
+ node = node.parent!;
assert(node != child); // indicates we are about to create a cycle
return true;
}());
adoptChild(child);
child._previousSibling = lastChild;
if (lastChild != null)
- lastChild._nextSibling = child;
+ lastChild!._nextSibling = child;
_lastChild = child;
_firstChild ??= child;
assert(child.attached == attached);
@@ -982,19 +976,19 @@
assert(_firstChild == child);
_firstChild = child._nextSibling;
} else {
- child._previousSibling._nextSibling = child.nextSibling;
+ child._previousSibling!._nextSibling = child.nextSibling;
}
if (child._nextSibling == null) {
assert(lastChild == child);
_lastChild = child.previousSibling;
} else {
- child.nextSibling._previousSibling = child.previousSibling;
+ child.nextSibling!._previousSibling = child.previousSibling;
}
assert((firstChild == null) == (lastChild == null));
- assert(firstChild == null || firstChild.attached == attached);
- assert(lastChild == null || lastChild.attached == attached);
- assert(firstChild == null || _debugUltimateNextSiblingOf(firstChild, equals: lastChild));
- assert(lastChild == null || _debugUltimatePreviousSiblingOf(lastChild, equals: firstChild));
+ assert(firstChild == null || firstChild!.attached == attached);
+ assert(lastChild == null || lastChild!.attached == attached);
+ assert(firstChild == null || _debugUltimateNextSiblingOf(firstChild!, equals: lastChild));
+ assert(lastChild == null || _debugUltimatePreviousSiblingOf(lastChild!, equals: firstChild));
child._previousSibling = null;
child._nextSibling = null;
dropChild(child);
@@ -1003,9 +997,9 @@
/// Removes all of this layer's children from its child list.
void removeAllChildren() {
- Layer child = firstChild;
+ Layer? child = firstChild;
while (child != null) {
- final Layer next = child.nextSibling;
+ final Layer? next = child.nextSibling;
child._previousSibling = null;
child._nextSibling = null;
assert(child.attached == attached);
@@ -1029,7 +1023,7 @@
/// their children using [addChildrenToScene], then reverse the aforementioned
/// effects before returning from [addToScene].
void addChildrenToScene(ui.SceneBuilder builder, [ Offset childOffset = Offset.zero ]) {
- Layer child = firstChild;
+ Layer? child = firstChild;
while (child != null) {
if (childOffset == Offset.zero) {
child._addToSceneWithRetainedRendering(builder);
@@ -1073,7 +1067,7 @@
///
/// Used by [FollowerLayer] to transform its child to a [LeaderLayer]'s
/// position.
- void applyTransform(Layer child, Matrix4 transform) {
+ void applyTransform(Layer? child, Matrix4 transform) {
assert(child != null);
assert(transform != null);
}
@@ -1084,7 +1078,7 @@
if (firstChild == null)
return <Layer>[];
final List<Layer> children = <Layer>[];
- Layer child = firstChild;
+ Layer? child = firstChild;
while(child != null) {
children.add(child);
if (child is ContainerLayer) {
@@ -1100,10 +1094,10 @@
final List<DiagnosticsNode> children = <DiagnosticsNode>[];
if (firstChild == null)
return children;
- Layer child = firstChild;
+ Layer? child = firstChild;
int count = 1;
while (true) {
- children.add(child.toDiagnosticsNode(name: 'child $count'));
+ children.add(child!.toDiagnosticsNode(name: 'child $count'));
if (child == lastChild)
break;
count += 1;
@@ -1146,13 +1140,12 @@
}
@override
- @protected
- bool findAnnotations<S>(AnnotationResult<S> result, Offset localPosition, { @required bool onlyFirst }) {
+ bool findAnnotations<S extends Object>(AnnotationResult<S> result, Offset localPosition, { required bool onlyFirst }) {
return super.findAnnotations<S>(result, localPosition - offset, onlyFirst: onlyFirst);
}
@override
- void applyTransform(Layer child, Matrix4 transform) {
+ void applyTransform(Layer? child, Matrix4 transform) {
assert(child != null);
assert(transform != null);
transform.multiply(Matrix4.translationValues(offset.dx, offset.dy, 0.0));
@@ -1168,7 +1161,7 @@
engineLayer = builder.pushOffset(
layerOffset.dx + offset.dx,
layerOffset.dy + offset.dy,
- oldLayer: _engineLayer as ui.OffsetEngineLayer,
+ oldLayer: _engineLayer as ui.OffsetEngineLayer?,
);
addChildrenToScene(builder);
builder.pop();
@@ -1235,7 +1228,7 @@
///
/// The [clipBehavior] argument must not be null, and must not be [Clip.none].
ClipRectLayer({
- Rect clipRect,
+ Rect? clipRect,
Clip clipBehavior = Clip.hardEdge,
}) : _clipRect = clipRect,
_clipBehavior = clipBehavior,
@@ -1246,9 +1239,9 @@
///
/// The scene must be explicitly recomposited after this property is changed
/// (as described at [Layer]).
- Rect get clipRect => _clipRect;
- Rect _clipRect;
- set clipRect(Rect value) {
+ Rect? get clipRect => _clipRect;
+ Rect? _clipRect;
+ set clipRect(Rect? value) {
if (value != _clipRect) {
_clipRect = value;
markNeedsAddToScene();
@@ -1274,9 +1267,8 @@
}
@override
- @protected
- bool findAnnotations<S>(AnnotationResult<S> result, Offset localPosition, { @required bool onlyFirst }) {
- if (!clipRect.contains(localPosition))
+ bool findAnnotations<S extends Object>(AnnotationResult<S> result, Offset localPosition, { required bool onlyFirst }) {
+ if (!clipRect!.contains(localPosition))
return false;
return super.findAnnotations<S>(result, localPosition, onlyFirst: onlyFirst);
}
@@ -1291,11 +1283,11 @@
return true;
}());
if (enabled) {
- final Rect shiftedClipRect = layerOffset == Offset.zero ? clipRect : clipRect.shift(layerOffset);
+ final Rect shiftedClipRect = layerOffset == Offset.zero ? clipRect! : clipRect!.shift(layerOffset);
engineLayer = builder.pushClipRect(
shiftedClipRect,
clipBehavior: clipBehavior,
- oldLayer: _engineLayer as ui.ClipRectEngineLayer,
+ oldLayer: _engineLayer as ui.ClipRectEngineLayer?,
);
} else {
engineLayer = null;
@@ -1324,7 +1316,7 @@
/// The [clipRRect] and [clipBehavior] properties must be non-null before the
/// compositing phase of the pipeline.
ClipRRectLayer({
- RRect clipRRect,
+ RRect? clipRRect,
Clip clipBehavior = Clip.antiAlias,
}) : _clipRRect = clipRRect,
_clipBehavior = clipBehavior,
@@ -1335,9 +1327,9 @@
///
/// The scene must be explicitly recomposited after this property is changed
/// (as described at [Layer]).
- RRect get clipRRect => _clipRRect;
- RRect _clipRRect;
- set clipRRect(RRect value) {
+ RRect? get clipRRect => _clipRRect;
+ RRect? _clipRRect;
+ set clipRRect(RRect? value) {
if (value != _clipRRect) {
_clipRRect = value;
markNeedsAddToScene();
@@ -1359,9 +1351,8 @@
}
@override
- @protected
- bool findAnnotations<S>(AnnotationResult<S> result, Offset localPosition, { @required bool onlyFirst }) {
- if (!clipRRect.contains(localPosition))
+ bool findAnnotations<S extends Object>(AnnotationResult<S> result, Offset localPosition, { required bool onlyFirst }) {
+ if (!clipRRect!.contains(localPosition))
return false;
return super.findAnnotations<S>(result, localPosition, onlyFirst: onlyFirst);
}
@@ -1376,11 +1367,11 @@
return true;
}());
if (enabled) {
- final RRect shiftedClipRRect = layerOffset == Offset.zero ? clipRRect : clipRRect.shift(layerOffset);
+ final RRect shiftedClipRRect = layerOffset == Offset.zero ? clipRRect! : clipRRect!.shift(layerOffset);
engineLayer = builder.pushClipRRect(
shiftedClipRRect,
clipBehavior: clipBehavior,
- oldLayer: _engineLayer as ui.ClipRRectEngineLayer,
+ oldLayer: _engineLayer as ui.ClipRRectEngineLayer?,
);
} else {
engineLayer = null;
@@ -1409,7 +1400,7 @@
/// The [clipPath] and [clipBehavior] properties must be non-null before the
/// compositing phase of the pipeline.
ClipPathLayer({
- Path clipPath,
+ Path? clipPath,
Clip clipBehavior = Clip.antiAlias,
}) : _clipPath = clipPath,
_clipBehavior = clipBehavior,
@@ -1420,9 +1411,9 @@
///
/// The scene must be explicitly recomposited after this property is changed
/// (as described at [Layer]).
- Path get clipPath => _clipPath;
- Path _clipPath;
- set clipPath(Path value) {
+ Path? get clipPath => _clipPath;
+ Path? _clipPath;
+ set clipPath(Path? value) {
if (value != _clipPath) {
_clipPath = value;
markNeedsAddToScene();
@@ -1444,9 +1435,8 @@
}
@override
- @protected
- bool findAnnotations<S>(AnnotationResult<S> result, Offset localPosition, { @required bool onlyFirst }) {
- if (!clipPath.contains(localPosition))
+ bool findAnnotations<S extends Object>(AnnotationResult<S> result, Offset localPosition, { required bool onlyFirst }) {
+ if (!clipPath!.contains(localPosition))
return false;
return super.findAnnotations<S>(result, localPosition, onlyFirst: onlyFirst);
}
@@ -1461,11 +1451,11 @@
return true;
}());
if (enabled) {
- final Path shiftedPath = layerOffset == Offset.zero ? clipPath : clipPath.shift(layerOffset);
+ final Path shiftedPath = layerOffset == Offset.zero ? clipPath! : clipPath!.shift(layerOffset);
engineLayer = builder.pushClipPath(
shiftedPath,
clipBehavior: clipBehavior,
- oldLayer: _engineLayer as ui.ClipPathEngineLayer,
+ oldLayer: _engineLayer as ui.ClipPathEngineLayer?,
);
} else {
engineLayer = null;
@@ -1489,16 +1479,16 @@
/// The [colorFilter] property must be non-null before the compositing phase
/// of the pipeline.
ColorFilterLayer({
- ColorFilter colorFilter,
+ ColorFilter? colorFilter,
}) : _colorFilter = colorFilter;
/// The color filter to apply to children.
///
/// The scene must be explicitly recomposited after this property is changed
/// (as described at [Layer]).
- ColorFilter get colorFilter => _colorFilter;
- ColorFilter _colorFilter;
- set colorFilter(ColorFilter value) {
+ ColorFilter? get colorFilter => _colorFilter;
+ ColorFilter? _colorFilter;
+ set colorFilter(ColorFilter? value) {
assert(value != null);
if (value != _colorFilter) {
_colorFilter = value;
@@ -1510,8 +1500,8 @@
void addToScene(ui.SceneBuilder builder, [ Offset layerOffset = Offset.zero ]) {
assert(colorFilter != null);
engineLayer = builder.pushColorFilter(
- colorFilter,
- oldLayer: _engineLayer as ui.ColorFilterEngineLayer,
+ colorFilter!,
+ oldLayer: _engineLayer as ui.ColorFilterEngineLayer?,
);
addChildrenToScene(builder, layerOffset);
builder.pop();
@@ -1531,16 +1521,16 @@
/// The [imageFilter] property must be non-null before the compositing phase
/// of the pipeline.
ImageFilterLayer({
- ui.ImageFilter imageFilter,
+ ui.ImageFilter? imageFilter,
}) : _imageFilter = imageFilter;
/// The image filter to apply to children.
///
/// The scene must be explicitly recomposited after this property is changed
/// (as described at [Layer]).
- ui.ImageFilter get imageFilter => _imageFilter;
- ui.ImageFilter _imageFilter;
- set imageFilter(ui.ImageFilter value) {
+ ui.ImageFilter? get imageFilter => _imageFilter;
+ ui.ImageFilter? _imageFilter;
+ set imageFilter(ui.ImageFilter? value) {
assert(value != null);
if (value != _imageFilter) {
_imageFilter = value;
@@ -1552,8 +1542,8 @@
void addToScene(ui.SceneBuilder builder, [ Offset layerOffset = Offset.zero ]) {
assert(imageFilter != null);
engineLayer = builder.pushImageFilter(
- imageFilter,
- oldLayer: _engineLayer as ui.ImageFilterEngineLayer,
+ imageFilter!,
+ oldLayer: _engineLayer as ui.ImageFilterEngineLayer?,
);
addChildrenToScene(builder, layerOffset);
builder.pop();
@@ -1576,7 +1566,7 @@
///
/// The [transform] and [offset] properties must be non-null before the
/// compositing phase of the pipeline.
- TransformLayer({ Matrix4 transform, Offset offset = Offset.zero })
+ TransformLayer({ Matrix4? transform, Offset offset = Offset.zero })
: _transform = transform,
super(offset: offset);
@@ -1589,11 +1579,11 @@
///
/// The [transform] property must be non-null before the compositing phase of
/// the pipeline.
- Matrix4 get transform => _transform;
- Matrix4 _transform;
- set transform(Matrix4 value) {
+ Matrix4? get transform => _transform;
+ Matrix4? _transform;
+ set transform(Matrix4? value) {
assert(value != null);
- assert(value.storage.every((double component) => component.isFinite));
+ assert(value!.storage.every((double component) => component.isFinite));
if (value == _transform)
return;
_transform = value;
@@ -1601,8 +1591,8 @@
markNeedsAddToScene();
}
- Matrix4 _lastEffectiveTransform;
- Matrix4 _invertedTransform;
+ Matrix4? _lastEffectiveTransform;
+ Matrix4? _invertedTransform;
bool _inverseDirty = true;
@override
@@ -1612,47 +1602,46 @@
final Offset totalOffset = offset + layerOffset;
if (totalOffset != Offset.zero) {
_lastEffectiveTransform = Matrix4.translationValues(totalOffset.dx, totalOffset.dy, 0.0)
- ..multiply(_lastEffectiveTransform);
+ ..multiply(_lastEffectiveTransform!);
}
engineLayer = builder.pushTransform(
- _lastEffectiveTransform.storage,
- oldLayer: _engineLayer as ui.TransformEngineLayer,
+ _lastEffectiveTransform!.storage,
+ oldLayer: _engineLayer as ui.TransformEngineLayer?,
);
addChildrenToScene(builder);
builder.pop();
}
- Offset _transformOffset(Offset localPosition) {
+ Offset? _transformOffset(Offset localPosition) {
if (_inverseDirty) {
_invertedTransform = Matrix4.tryInvert(
- PointerEvent.removePerspectiveTransform(transform)
+ PointerEvent.removePerspectiveTransform(transform!)
);
_inverseDirty = false;
}
if (_invertedTransform == null)
return null;
- return MatrixUtils.transformPoint(_invertedTransform, localPosition);
+ return MatrixUtils.transformPoint(_invertedTransform!, localPosition);
}
@override
- @protected
- bool findAnnotations<S>(AnnotationResult<S> result, Offset localPosition, { @required bool onlyFirst }) {
- final Offset transformedOffset = _transformOffset(localPosition);
+ bool findAnnotations<S extends Object>(AnnotationResult<S> result, Offset localPosition, { required bool onlyFirst }) {
+ final Offset? transformedOffset = _transformOffset(localPosition);
if (transformedOffset == null)
return false;
return super.findAnnotations<S>(result, transformedOffset, onlyFirst: onlyFirst);
}
@override
- void applyTransform(Layer child, Matrix4 transform) {
+ void applyTransform(Layer? child, Matrix4 transform) {
assert(child != null);
assert(transform != null);
assert(_lastEffectiveTransform != null || this.transform != null);
if (_lastEffectiveTransform == null) {
- transform.multiply(this.transform);
+ transform.multiply(this.transform!);
} else {
- transform.multiply(_lastEffectiveTransform);
+ transform.multiply(_lastEffectiveTransform!);
}
}
@@ -1677,7 +1666,7 @@
/// The [alpha] property must be non-null before the compositing phase of
/// the pipeline.
OpacityLayer({
- int alpha,
+ int? alpha,
Offset offset = Offset.zero,
}) : _alpha = alpha,
_offset = offset;
@@ -1689,9 +1678,9 @@
///
/// The scene must be explicitly recomposited after this property is changed
/// (as described at [Layer]).
- int get alpha => _alpha;
- int _alpha;
- set alpha(int value) {
+ int? get alpha => _alpha;
+ int? _alpha;
+ set alpha(int? value) {
assert(value != null);
if (value != _alpha) {
_alpha = value;
@@ -1700,9 +1689,9 @@
}
/// Offset from parent in the parent's coordinate system.
- Offset get offset => _offset;
- Offset _offset;
- set offset(Offset value) {
+ Offset? get offset => _offset;
+ Offset? _offset;
+ set offset(Offset? value) {
if (value != _offset) {
_offset = value;
markNeedsAddToScene();
@@ -1710,10 +1699,10 @@
}
@override
- void applyTransform(Layer child, Matrix4 transform) {
+ void applyTransform(Layer? child, Matrix4 transform) {
assert(child != null);
assert(transform != null);
- transform.translate(offset.dx, offset.dy);
+ transform.translate(offset!.dx, offset!.dy);
}
@override
@@ -1727,9 +1716,9 @@
if (enabled)
engineLayer = builder.pushOpacity(
- alpha,
- offset: offset + layerOffset,
- oldLayer: _engineLayer as ui.OpacityEngineLayer,
+ alpha!,
+ offset: offset! + layerOffset,
+ oldLayer: _engineLayer as ui.OpacityEngineLayer?,
);
else
engineLayer = null;
@@ -1758,9 +1747,9 @@
/// The [shader], [maskRect], and [blendMode] properties must be non-null
/// before the compositing phase of the pipeline.
ShaderMaskLayer({
- Shader shader,
- Rect maskRect,
- BlendMode blendMode,
+ Shader? shader,
+ Rect? maskRect,
+ BlendMode? blendMode,
}) : _shader = shader,
_maskRect = maskRect,
_blendMode = blendMode;
@@ -1777,9 +1766,9 @@
/// See also:
///
/// * [ui.Gradient] and [ui.ImageShader], two shader types that can be used.
- Shader get shader => _shader;
- Shader _shader;
- set shader(Shader value) {
+ Shader? get shader => _shader;
+ Shader? _shader;
+ set shader(Shader? value) {
if (value != _shader) {
_shader = value;
markNeedsAddToScene();
@@ -1793,9 +1782,9 @@
///
/// The scene must be explicitly recomposited after this property is changed
/// (as described at [Layer]).
- Rect get maskRect => _maskRect;
- Rect _maskRect;
- set maskRect(Rect value) {
+ Rect? get maskRect => _maskRect;
+ Rect? _maskRect;
+ set maskRect(Rect? value) {
if (value != _maskRect) {
_maskRect = value;
markNeedsAddToScene();
@@ -1806,9 +1795,9 @@
///
/// The scene must be explicitly recomposited after this property is changed
/// (as described at [Layer]).
- BlendMode get blendMode => _blendMode;
- BlendMode _blendMode;
- set blendMode(BlendMode value) {
+ BlendMode? get blendMode => _blendMode;
+ BlendMode? _blendMode;
+ set blendMode(BlendMode? value) {
if (value != _blendMode) {
_blendMode = value;
markNeedsAddToScene();
@@ -1821,12 +1810,12 @@
assert(maskRect != null);
assert(blendMode != null);
assert(layerOffset != null);
- final Rect shiftedMaskRect = layerOffset == Offset.zero ? maskRect : maskRect.shift(layerOffset);
+ final Rect shiftedMaskRect = layerOffset == Offset.zero ? maskRect! : maskRect!.shift(layerOffset);
engineLayer = builder.pushShaderMask(
- shader,
+ shader!,
shiftedMaskRect,
- blendMode,
- oldLayer: _engineLayer as ui.ShaderMaskEngineLayer,
+ blendMode!,
+ oldLayer: _engineLayer as ui.ShaderMaskEngineLayer?,
);
addChildrenToScene(builder, layerOffset);
builder.pop();
@@ -1847,15 +1836,15 @@
///
/// The [filter] property must be non-null before the compositing phase of the
/// pipeline.
- BackdropFilterLayer({ ui.ImageFilter filter }) : _filter = filter;
+ BackdropFilterLayer({ ui.ImageFilter? filter }) : _filter = filter;
/// The filter to apply to the existing contents of the scene.
///
/// The scene must be explicitly recomposited after this property is changed
/// (as described at [Layer]).
- ui.ImageFilter get filter => _filter;
- ui.ImageFilter _filter;
- set filter(ui.ImageFilter value) {
+ ui.ImageFilter? get filter => _filter;
+ ui.ImageFilter? _filter;
+ set filter(ui.ImageFilter? value) {
if (value != _filter) {
_filter = value;
markNeedsAddToScene();
@@ -1866,8 +1855,8 @@
void addToScene(ui.SceneBuilder builder, [ Offset layerOffset = Offset.zero ]) {
assert(filter != null);
engineLayer = builder.pushBackdropFilter(
- filter,
- oldLayer: _engineLayer as ui.BackdropFilterEngineLayer,
+ filter!,
+ oldLayer: _engineLayer as ui.BackdropFilterEngineLayer?,
);
addChildrenToScene(builder, layerOffset);
builder.pop();
@@ -1890,11 +1879,11 @@
/// The [clipPath], [clipBehavior], [elevation], [color], and [shadowColor]
/// arguments must be non-null before the compositing phase of the pipeline.
PhysicalModelLayer({
- Path clipPath,
+ Path? clipPath,
Clip clipBehavior = Clip.none,
- double elevation,
- Color color,
- Color shadowColor,
+ double? elevation,
+ Color? color,
+ Color? shadowColor,
}) : _clipPath = clipPath,
_clipBehavior = clipBehavior,
_elevation = elevation,
@@ -1905,9 +1894,9 @@
///
/// The scene must be explicitly recomposited after this property is changed
/// (as described at [Layer]).
- Path get clipPath => _clipPath;
- Path _clipPath;
- set clipPath(Path value) {
+ Path? get clipPath => _clipPath;
+ Path? _clipPath;
+ set clipPath(Path? value) {
if (value != _clipPath) {
_clipPath = value;
markNeedsAddToScene();
@@ -1915,13 +1904,13 @@
}
Path get _debugTransformedClipPath {
- ContainerLayer ancestor = parent;
+ ContainerLayer? ancestor = parent;
final Matrix4 matrix = Matrix4.identity();
while (ancestor != null && ancestor.parent != null) {
ancestor.applyTransform(this, matrix);
ancestor = ancestor.parent;
}
- return clipPath.transform(matrix.storage);
+ return clipPath!.transform(matrix.storage);
}
/// {@macro flutter.widgets.Clip}
@@ -1945,9 +1934,9 @@
/// flag is set. For this reason, this property will often be set to zero in
/// tests even if the layer should be raised. To verify the actual value,
/// consider setting [debugDisableShadows] to false in your test.
- double get elevation => _elevation;
- double _elevation;
- set elevation(double value) {
+ double? get elevation => _elevation;
+ double? _elevation;
+ set elevation(double? value) {
if (value != _elevation) {
_elevation = value;
markNeedsAddToScene();
@@ -1958,9 +1947,9 @@
///
/// The scene must be explicitly recomposited after this property is changed
/// (as described at [Layer]).
- Color get color => _color;
- Color _color;
- set color(Color value) {
+ Color? get color => _color;
+ Color? _color;
+ set color(Color? value) {
if (value != _color) {
_color = value;
markNeedsAddToScene();
@@ -1968,9 +1957,9 @@
}
/// The shadow color.
- Color get shadowColor => _shadowColor;
- Color _shadowColor;
- set shadowColor(Color value) {
+ Color? get shadowColor => _shadowColor;
+ Color? _shadowColor;
+ set shadowColor(Color? value) {
if (value != _shadowColor) {
_shadowColor = value;
markNeedsAddToScene();
@@ -1978,9 +1967,8 @@
}
@override
- @protected
- bool findAnnotations<S>(AnnotationResult<S> result, Offset localPosition, { @required bool onlyFirst }) {
- if (!clipPath.contains(localPosition))
+ bool findAnnotations<S extends Object>(AnnotationResult<S> result, Offset localPosition, { required bool onlyFirst }) {
+ if (!clipPath!.contains(localPosition))
return false;
return super.findAnnotations<S>(result, localPosition, onlyFirst: onlyFirst);
}
@@ -2000,12 +1988,12 @@
}());
if (enabled) {
engineLayer = builder.pushPhysicalShape(
- path: layerOffset == Offset.zero ? clipPath : clipPath.shift(layerOffset),
- elevation: elevation,
- color: color,
+ path: layerOffset == Offset.zero ? clipPath! : clipPath!.shift(layerOffset),
+ elevation: elevation!,
+ color: color!,
shadowColor: shadowColor,
clipBehavior: clipBehavior,
- oldLayer: _engineLayer as ui.PhysicalShapeEngineLayer,
+ oldLayer: _engineLayer as ui.PhysicalShapeEngineLayer?,
);
} else {
engineLayer = null;
@@ -2037,8 +2025,8 @@
/// render objects.
class LayerLink {
/// The currently-registered [LeaderLayer], if any.
- LeaderLayer get leader => _leader;
- LeaderLayer _leader;
+ LeaderLayer? get leader => _leader;
+ LeaderLayer? _leader;
@override
String toString() => '${describeIdentity(this)}(${ _leader != null ? "<linked>" : "<dangling>" })';
@@ -2058,7 +2046,7 @@
///
/// The [offset] property must be non-null before the compositing phase of the
/// pipeline.
- LeaderLayer({ @required LayerLink link, this.offset = Offset.zero }) : assert(link != null), _link = link;
+ LeaderLayer({ required LayerLink link, this.offset = Offset.zero }) : assert(link != null), _link = link;
/// The object with which this layer should register.
///
@@ -2105,11 +2093,10 @@
/// This is reset to null when the layer is attached or detached, to help
/// catch cases where the follower layer ends up before the leader layer, but
/// not every case can be detected.
- Offset _lastOffset;
+ Offset? _lastOffset;
@override
- @protected
- bool findAnnotations<S>(AnnotationResult<S> result, Offset localPosition, { @required bool onlyFirst }) {
+ bool findAnnotations<S extends Object>(AnnotationResult<S> result, Offset localPosition, { required bool onlyFirst }) {
return super.findAnnotations<S>(result, localPosition - offset, onlyFirst: onlyFirst);
}
@@ -2119,8 +2106,8 @@
_lastOffset = offset + layerOffset;
if (_lastOffset != Offset.zero)
engineLayer = builder.pushTransform(
- Matrix4.translationValues(_lastOffset.dx, _lastOffset.dy, 0.0).storage,
- oldLayer: _engineLayer as ui.TransformEngineLayer,
+ Matrix4.translationValues(_lastOffset!.dx, _lastOffset!.dy, 0.0).storage,
+ oldLayer: _engineLayer as ui.TransformEngineLayer?,
);
addChildrenToScene(builder);
if (_lastOffset != Offset.zero)
@@ -2135,10 +2122,10 @@
/// The `child` argument may be null, as the same transform is applied to all
/// children.
@override
- void applyTransform(Layer child, Matrix4 transform) {
+ void applyTransform(Layer? child, Matrix4 transform) {
assert(_lastOffset != null);
if (_lastOffset != Offset.zero)
- transform.translate(_lastOffset.dx, _lastOffset.dy);
+ transform.translate(_lastOffset!.dx, _lastOffset!.dy);
}
@override
@@ -2167,7 +2154,7 @@
/// The [unlinkedOffset], [linkedOffset], and [showWhenUnlinked] properties
/// must be non-null before the compositing phase of the pipeline.
FollowerLayer({
- @required LayerLink link,
+ required LayerLink link,
this.showWhenUnlinked = true,
this.unlinkedOffset = Offset.zero,
this.linkedOffset = Offset.zero,
@@ -2197,7 +2184,7 @@
///
/// The [showWhenUnlinked] property must be non-null before the compositing
/// phase of the pipeline.
- bool showWhenUnlinked;
+ bool? showWhenUnlinked;
/// Offset from parent in the parent's coordinate system, used when the layer
/// is not linked to a [LeaderLayer].
@@ -2211,7 +2198,7 @@
/// See also:
///
/// * [linkedOffset], for when the layers are linked.
- Offset unlinkedOffset;
+ Offset? unlinkedOffset;
/// Offset from the origin of the leader layer to the origin of the child
/// layers, used when the layer is linked to a [LeaderLayer].
@@ -2225,35 +2212,34 @@
/// See also:
///
/// * [unlinkedOffset], for when the layer is not linked.
- Offset linkedOffset;
+ Offset? linkedOffset;
- Offset _lastOffset;
- Matrix4 _lastTransform;
- Matrix4 _invertedTransform;
+ Offset? _lastOffset;
+ Matrix4? _lastTransform;
+ Matrix4? _invertedTransform;
bool _inverseDirty = true;
- Offset _transformOffset<S>(Offset localPosition) {
+ Offset? _transformOffset<S extends Object>(Offset localPosition) {
if (_inverseDirty) {
- _invertedTransform = Matrix4.tryInvert(getLastTransform());
+ _invertedTransform = Matrix4.tryInvert(getLastTransform()!);
_inverseDirty = false;
}
if (_invertedTransform == null)
return null;
final Vector4 vector = Vector4(localPosition.dx, localPosition.dy, 0.0, 1.0);
- final Vector4 result = _invertedTransform.transform(vector);
- return Offset(result[0] - linkedOffset.dx, result[1] - linkedOffset.dy);
+ final Vector4 result = _invertedTransform!.transform(vector);
+ return Offset(result[0] - linkedOffset!.dx, result[1] - linkedOffset!.dy);
}
@override
- @protected
- bool findAnnotations<S>(AnnotationResult<S> result, Offset localPosition, { @required bool onlyFirst }) {
+ bool findAnnotations<S extends Object>(AnnotationResult<S> result, Offset localPosition, { required bool onlyFirst }) {
if (link.leader == null) {
- if (showWhenUnlinked) {
- return super.findAnnotations(result, localPosition - unlinkedOffset, onlyFirst: onlyFirst);
+ if (showWhenUnlinked!) {
+ return super.findAnnotations(result, localPosition - unlinkedOffset!, onlyFirst: onlyFirst);
}
return false;
}
- final Offset transformedOffset = _transformOffset<S>(localPosition);
+ final Offset? transformedOffset = _transformOffset<S>(localPosition);
if (transformedOffset == null) {
return false;
}
@@ -2266,11 +2252,11 @@
/// a degenerate matrix applied, then this will be null.
///
/// This method returns a new [Matrix4] instance each time it is invoked.
- Matrix4 getLastTransform() {
+ Matrix4? getLastTransform() {
if (_lastTransform == null)
return null;
- final Matrix4 result = Matrix4.translationValues(-_lastOffset.dx, -_lastOffset.dy, 0.0);
- result.multiply(_lastTransform);
+ final Matrix4 result = Matrix4.translationValues(-_lastOffset!.dx, -_lastOffset!.dy, 0.0);
+ result.multiply(_lastTransform!);
return result;
}
@@ -2280,13 +2266,13 @@
/// treated as the child of the second, and so forth. The first layer in the
/// list won't have [applyTransform] called on it. The first layer may be
/// null.
- Matrix4 _collectTransformForLayerChain(List<ContainerLayer> layers) {
+ Matrix4 _collectTransformForLayerChain(List<ContainerLayer?> layers) {
// Initialize our result matrix.
final Matrix4 result = Matrix4.identity();
// Apply each layer to the matrix in turn, starting from the last layer,
// and providing the previous layer as the child.
for (int index = layers.length - 1; index > 0; index -= 1)
- layers[index].applyTransform(layers[index - 1], result);
+ layers[index]!.applyTransform(layers[index - 1], result);
return result;
}
@@ -2298,30 +2284,30 @@
if (link.leader == null)
return;
// If we're linked, check the link is valid.
- assert(link.leader.owner == owner, 'Linked LeaderLayer anchor is not in the same layer tree as the FollowerLayer.');
- assert(link.leader._lastOffset != null, 'LeaderLayer anchor must come before FollowerLayer in paint order, but the reverse was true.');
+ assert(link.leader!.owner == owner, 'Linked LeaderLayer anchor is not in the same layer tree as the FollowerLayer.');
+ assert(link.leader!._lastOffset != null, 'LeaderLayer anchor must come before FollowerLayer in paint order, but the reverse was true.');
// Collect all our ancestors into a Set so we can recognize them.
final Set<Layer> ancestors = HashSet<Layer>();
- Layer ancestor = parent;
+ Layer? ancestor = parent;
while (ancestor != null) {
ancestors.add(ancestor);
ancestor = ancestor.parent;
}
// Collect all the layers from a hypothetical child (null) of the target
// layer up to the common ancestor layer.
- ContainerLayer layer = link.leader;
- final List<ContainerLayer> forwardLayers = <ContainerLayer>[null, layer];
+ ContainerLayer? layer = link.leader;
+ final List<ContainerLayer?> forwardLayers = <ContainerLayer?>[null, layer];
do {
- layer = layer.parent;
+ layer = layer!.parent;
forwardLayers.add(layer);
- } while (!ancestors.contains(layer));
+ } while (!ancestors.contains(layer)); // ignore: iterable_contains_unrelated_type
ancestor = layer;
// Collect all the layers from this layer up to the common ancestor layer.
layer = this;
final List<ContainerLayer> inverseLayers = <ContainerLayer>[layer];
do {
- layer = layer.parent;
- inverseLayers.add(layer);
+ layer = layer!.parent;
+ inverseLayers.add(layer!);
} while (layer != ancestor);
// Establish the forward and backward matrices given these lists of layers.
final Matrix4 forwardTransform = _collectTransformForLayerChain(forwardLayers);
@@ -2332,7 +2318,7 @@
}
// Combine the matrices and store the result.
inverseTransform.multiply(forwardTransform);
- inverseTransform.translate(linkedOffset.dx, linkedOffset.dy);
+ inverseTransform.translate(linkedOffset!.dx, linkedOffset!.dy);
_lastTransform = inverseTransform;
_inverseDirty = true;
}
@@ -2354,7 +2340,7 @@
void addToScene(ui.SceneBuilder builder, [ Offset layerOffset = Offset.zero ]) {
assert(link != null);
assert(showWhenUnlinked != null);
- if (link.leader == null && !showWhenUnlinked) {
+ if (link.leader == null && !showWhenUnlinked!) {
_lastTransform = null;
_lastOffset = null;
_inverseDirty = true;
@@ -2364,15 +2350,15 @@
_establishTransform();
if (_lastTransform != null) {
engineLayer = builder.pushTransform(
- _lastTransform.storage,
+ _lastTransform!.storage,
oldLayer: _engineLayer as ui.TransformEngineLayer,
);
addChildrenToScene(builder);
builder.pop();
- _lastOffset = unlinkedOffset + layerOffset;
+ _lastOffset = unlinkedOffset! + layerOffset;
} else {
_lastOffset = null;
- final Matrix4 matrix = Matrix4.translationValues(unlinkedOffset.dx, unlinkedOffset.dy, .0);
+ final Matrix4 matrix = Matrix4.translationValues(unlinkedOffset!.dx, unlinkedOffset!.dy, .0);
engineLayer = builder.pushTransform(
matrix.storage,
oldLayer: _engineLayer as ui.TransformEngineLayer,
@@ -2384,13 +2370,13 @@
}
@override
- void applyTransform(Layer child, Matrix4 transform) {
+ void applyTransform(Layer? child, Matrix4 transform) {
assert(child != null);
assert(transform != null);
if (_lastTransform != null) {
- transform.multiply(_lastTransform);
+ transform.multiply(_lastTransform!);
} else {
- transform.multiply(Matrix4.translationValues(unlinkedOffset.dx, unlinkedOffset.dy, .0));
+ transform.multiply(Matrix4.translationValues(unlinkedOffset!.dx, unlinkedOffset!.dy, 0));
}
}
@@ -2423,14 +2409,14 @@
///
/// This layer is opaque to a type of annotation if any child is also opaque, or
/// if [opaque] is true and the layer's annotation is added.
-class AnnotatedRegionLayer<T> extends ContainerLayer {
+class AnnotatedRegionLayer<T extends Object> extends ContainerLayer {
/// Creates a new layer that annotates its children with [value].
///
/// The [value] provided cannot be null.
AnnotatedRegionLayer(
this.value, {
this.size,
- Offset offset,
+ Offset? offset,
this.opaque = false,
}) : assert(value != null),
assert(opaque != null),
@@ -2446,7 +2432,7 @@
/// position is contained by the rectangle formed by [size] and [offset].
/// Otherwise no such restriction is applied, and clipping can only be done by
/// the ancestor layers.
- final Size size;
+ final Size? size;
/// The position of the annotated object.
///
@@ -2504,12 +2490,11 @@
/// For explanation of layer annotations, parameters and return value, refer
/// to [Layer.findAnnotations].
@override
- @protected
- bool findAnnotations<S>(AnnotationResult<S> result, Offset localPosition, { @required bool onlyFirst }) {
+ bool findAnnotations<S extends Object>(AnnotationResult<S> result, Offset localPosition, { required bool onlyFirst }) {
bool isAbsorbed = super.findAnnotations(result, localPosition, onlyFirst: onlyFirst);
if (result.entries.isNotEmpty && onlyFirst)
return isAbsorbed;
- if (size != null && !(offset & size).contains(localPosition)) {
+ if (size != null && !(offset & size!).contains(localPosition)) {
return isAbsorbed;
}
if (T == S) {
diff --git a/packages/flutter/lib/src/rendering/list_body.dart b/packages/flutter/lib/src/rendering/list_body.dart
index 3ace7da..5db7834 100644
--- a/packages/flutter/lib/src/rendering/list_body.dart
+++ b/packages/flutter/lib/src/rendering/list_body.dart
@@ -2,8 +2,6 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-// @dart = 2.8
-
import 'dart:math' as math;
import 'box.dart';
@@ -32,7 +30,7 @@
///
/// By default, children are arranged along the vertical axis.
RenderListBody({
- List<RenderBox> children,
+ List<RenderBox>? children,
AxisDirection axisDirection = AxisDirection.down,
}) : assert(axisDirection != null),
_axisDirection = axisDirection {
@@ -123,7 +121,7 @@
]);
}());
double mainAxisExtent = 0.0;
- RenderBox child = firstChild;
+ RenderBox? child = firstChild;
switch (axisDirection) {
case AxisDirection.right:
final BoxConstraints innerConstraints = BoxConstraints.tightFor(height: constraints.maxHeight);
@@ -201,7 +199,7 @@
double _getIntrinsicCrossAxis(_ChildSizingFunction childSize) {
double extent = 0.0;
- RenderBox child = firstChild;
+ RenderBox? child = firstChild;
while (child != null) {
extent = math.max(extent, childSize(child));
final ListBodyParentData childParentData = child.parentData as ListBodyParentData;
@@ -212,7 +210,7 @@
double _getIntrinsicMainAxis(_ChildSizingFunction childSize) {
double extent = 0.0;
- RenderBox child = firstChild;
+ RenderBox? child = firstChild;
while (child != null) {
extent += childSize(child);
final ListBodyParentData childParentData = child.parentData as ListBodyParentData;
@@ -230,7 +228,6 @@
case Axis.vertical:
return _getIntrinsicCrossAxis((RenderBox child) => child.getMinIntrinsicWidth(height));
}
- return null;
}
@override
@@ -242,7 +239,6 @@
case Axis.vertical:
return _getIntrinsicCrossAxis((RenderBox child) => child.getMaxIntrinsicWidth(height));
}
- return null;
}
@override
@@ -254,7 +250,6 @@
case Axis.vertical:
return _getIntrinsicCrossAxis((RenderBox child) => child.getMinIntrinsicHeight(width));
}
- return null;
}
@override
@@ -266,11 +261,10 @@
case Axis.vertical:
return _getIntrinsicCrossAxis((RenderBox child) => child.getMaxIntrinsicHeight(width));
}
- return null;
}
@override
- double computeDistanceToActualBaseline(TextBaseline baseline) {
+ double? computeDistanceToActualBaseline(TextBaseline baseline) {
return defaultComputeDistanceToFirstActualBaseline(baseline);
}
@@ -280,7 +274,7 @@
}
@override
- bool hitTestChildren(BoxHitTestResult result, { Offset position }) {
+ bool hitTestChildren(BoxHitTestResult result, { required Offset position }) {
return defaultHitTestChildren(result, position: position);
}
diff --git a/packages/flutter/lib/src/rendering/list_wheel_viewport.dart b/packages/flutter/lib/src/rendering/list_wheel_viewport.dart
index 3b59584..ae35eee 100644
--- a/packages/flutter/lib/src/rendering/list_wheel_viewport.dart
+++ b/packages/flutter/lib/src/rendering/list_wheel_viewport.dart
@@ -2,12 +2,9 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-// @dart = 2.8
-
import 'dart:math' as math;
import 'package:flutter/animation.dart';
-import 'package:flutter/foundation.dart';
import 'package:vector_math/vector_math_64.dart' show Matrix4;
import 'box.dart';
@@ -30,7 +27,7 @@
/// If null, then there's no explicit limits to the range of the children
/// except that it has to be contiguous. If [childExistsAt] for a certain
/// index returns false, that index is already past the limit.
- int get childCount;
+ int? get childCount;
/// Checks whether the delegate is able to provide a child widget at the given
/// index.
@@ -44,7 +41,7 @@
/// nothing.
///
/// It is possible to create children with negative indices.
- void createChild(int index, { @required RenderBox after });
+ void createChild(int index, { required RenderBox? after });
/// Removes the child element corresponding with the given RenderBox.
void removeChild(RenderBox child);
@@ -53,7 +50,9 @@
/// [ParentData] for use with [RenderListWheelViewport].
class ListWheelParentData extends ContainerBoxParentData<RenderBox> {
/// Index of this child in its parent's child list.
- int index;
+ ///
+ /// This must be maintained by the [ListWheelChildManager].
+ int? index;
}
/// Render, onto a wheel, a bigger sequential set of objects inside this viewport.
@@ -135,19 +134,19 @@
///
/// All arguments must not be null. Optional arguments have reasonable defaults.
RenderListWheelViewport({
- @required this.childManager,
- @required ViewportOffset offset,
+ required this.childManager,
+ required ViewportOffset offset,
double diameterRatio = defaultDiameterRatio,
double perspective = defaultPerspective,
double offAxisFraction = 0,
bool useMagnifier = false,
double magnification = 1,
double overAndUnderCenterOpacity = 1,
- @required double itemExtent,
+ required double itemExtent,
double squeeze = 1,
bool renderChildrenOutsideViewport = false,
Clip clipBehavior = Clip.none,
- List<RenderBox> children,
+ List<RenderBox>? children,
}) : assert(childManager != null),
assert(offset != null),
assert(diameterRatio != null),
@@ -208,6 +207,8 @@
'rendered outside will be clipped anyway.';
/// The delegate that manages the children of this object.
+ ///
+ /// This delegate must maintain the [ListWheelParentData.index] value.
final ListWheelChildManager childManager;
/// The associated ViewportOffset object for the viewport describing the part
@@ -530,7 +531,7 @@
if (childManager.childCount == null)
return double.infinity;
- return math.max(0.0, (childManager.childCount - 1) * _itemExtent);
+ return math.max(0.0, (childManager.childCount! - 1) * _itemExtent);
}
/// Scroll extent distance in the untransformed plane between the center
@@ -567,7 +568,7 @@
double _getIntrinsicCrossAxis(_ChildSizingFunction childSize) {
double extent = 0.0;
- RenderBox child = firstChild;
+ RenderBox? child = firstChild;
while (child != null) {
extent = math.max(extent, childSize(child));
child = childAfter(child);
@@ -593,14 +594,14 @@
double computeMinIntrinsicHeight(double width) {
if (childManager.childCount == null)
return 0.0;
- return childManager.childCount * _itemExtent;
+ return childManager.childCount! * _itemExtent;
}
@override
double computeMaxIntrinsicHeight(double width) {
if (childManager.childCount == null)
return 0.0;
- return childManager.childCount * _itemExtent;
+ return childManager.childCount! * _itemExtent;
}
@override
@@ -611,12 +612,14 @@
size = constraints.biggest;
}
- /// Gets the index of a child by looking at its parentData.
+ /// Gets the index of a child by looking at its [parentData].
+ ///
+ /// This relies on the [childManager] maintaining [ListWheelParentData.index].
int indexOf(RenderBox child) {
assert(child != null);
final ListWheelParentData childParentData = child.parentData as ListWheelParentData;
assert(childParentData.index != null);
- return childParentData.index;
+ return childParentData.index!;
}
/// Returns the index of the child at the given offset.
@@ -625,7 +628,7 @@
/// Returns the scroll offset of the child with the given index.
double indexToScrollOffset(int index) => index * itemExtent;
- void _createChild(int index, { RenderBox after }) {
+ void _createChild(int index, { RenderBox? after }) {
invokeLayoutCallback<BoxConstraints>((BoxConstraints constraints) {
assert(constraints == this.constraints);
childManager.createChild(index, after: after);
@@ -697,7 +700,7 @@
// return.
if (targetFirstIndex > targetLastIndex) {
while (firstChild != null)
- _destroyChild(firstChild);
+ _destroyChild(firstChild!);
return;
}
@@ -711,34 +714,34 @@
// Case when there is no intersection.
if (childCount > 0 &&
- (indexOf(firstChild) > targetLastIndex || indexOf(lastChild) < targetFirstIndex)) {
+ (indexOf(firstChild!) > targetLastIndex || indexOf(lastChild!) < targetFirstIndex)) {
while (firstChild != null)
- _destroyChild(firstChild);
+ _destroyChild(firstChild!);
}
// If there is no child at this stage, we add the first one that is in
// target range.
if (childCount == 0) {
_createChild(targetFirstIndex);
- _layoutChild(firstChild, childConstraints, targetFirstIndex);
+ _layoutChild(firstChild!, childConstraints, targetFirstIndex);
}
- int currentFirstIndex = indexOf(firstChild);
- int currentLastIndex = indexOf(lastChild);
+ int currentFirstIndex = indexOf(firstChild!);
+ int currentLastIndex = indexOf(lastChild!);
// Remove all unnecessary children by shortening the current child list, in
// both directions.
while (currentFirstIndex < targetFirstIndex) {
- _destroyChild(firstChild);
+ _destroyChild(firstChild!);
currentFirstIndex++;
}
while (currentLastIndex > targetLastIndex) {
- _destroyChild(lastChild);
+ _destroyChild(lastChild!);
currentLastIndex--;
}
// Relayout all active children.
- RenderBox child = firstChild;
+ RenderBox? child = firstChild;
while (child != null) {
child.layout(childConstraints, parentUsesSize: true);
child = childAfter(child);
@@ -747,11 +750,11 @@
// Spawning new children that are actually visible but not in child list yet.
while (currentFirstIndex > targetFirstIndex) {
_createChild(currentFirstIndex - 1);
- _layoutChild(firstChild, childConstraints, --currentFirstIndex);
+ _layoutChild(firstChild!, childConstraints, --currentFirstIndex);
}
while (currentLastIndex < targetLastIndex) {
_createChild(currentLastIndex + 1, after: lastChild);
- _layoutChild(lastChild, childConstraints, ++currentLastIndex);
+ _layoutChild(lastChild!, childConstraints, ++currentLastIndex);
}
offset.applyViewportDimension(_viewportExtent);
@@ -796,13 +799,11 @@
/// Paints all children visible in the current viewport.
void _paintVisibleChildren(PaintingContext context, Offset offset) {
- RenderBox childToPaint = firstChild;
- ListWheelParentData childParentData = childToPaint?.parentData as ListWheelParentData;
-
- while (childParentData != null) {
+ RenderBox? childToPaint = firstChild;
+ while (childToPaint != null) {
+ final ListWheelParentData childParentData = childToPaint.parentData! as ListWheelParentData;
_paintTransformedChild(childToPaint, context, offset, childParentData.offset);
childToPaint = childAfter(childToPaint);
- childParentData = childToPaint?.parentData as ListWheelParentData;
}
}
@@ -988,23 +989,23 @@
/// painting coordinates** system.
@override
void applyPaintTransform(RenderBox child, Matrix4 transform) {
- final ListWheelParentData parentData = child?.parentData as ListWheelParentData;
+ final ListWheelParentData parentData = child.parentData as ListWheelParentData;
transform.translate(0.0, _getUntransformedPaintingCoordinateY(parentData.offset.dy));
}
@override
- Rect describeApproximatePaintClip(RenderObject child) {
- if (child != null && _shouldClipAtCurrentOffset()) {
+ Rect? describeApproximatePaintClip(RenderObject child) {
+ if (_shouldClipAtCurrentOffset()) {
return Offset.zero & size;
}
return null;
}
@override
- bool hitTestChildren(BoxHitTestResult result, { Offset position }) => false;
+ bool hitTestChildren(BoxHitTestResult result, { required Offset position }) => false;
@override
- RevealedOffset getOffsetToReveal(RenderObject target, double alignment, { Rect rect }) {
+ RevealedOffset getOffsetToReveal(RenderObject target, double alignment, { Rect? rect }) {
// `target` is only fully revealed when in the selected/center position. Therefore,
// this method always returns the offset that shows `target` in the center position,
// which is the same offset for all `alignment` values.
@@ -1028,8 +1029,8 @@
@override
void showOnScreen({
- RenderObject descendant,
- Rect rect,
+ RenderObject? descendant,
+ Rect? rect,
Duration duration = Duration.zero,
Curve curve = Curves.ease,
}) {
diff --git a/packages/flutter/lib/src/rendering/mouse_cursor.dart b/packages/flutter/lib/src/rendering/mouse_cursor.dart
index eabddb0..ceb2e1f 100644
--- a/packages/flutter/lib/src/rendering/mouse_cursor.dart
+++ b/packages/flutter/lib/src/rendering/mouse_cursor.dart
@@ -2,8 +2,6 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-// @dart = 2.8
-
import 'dart:async';
import 'package:flutter/foundation.dart';
@@ -27,8 +25,8 @@
/// Only valid when asserts are enabled. In release builds, always returns
/// null.
@visibleForTesting
- MouseCursor debugDeviceActiveCursor(int device) {
- MouseCursor result;
+ MouseCursor? debugDeviceActiveCursor(int device) {
+ MouseCursor? result;
assert(() {
result = _lastSession[device]?.cursor;
return true;
@@ -66,7 +64,7 @@
return;
}
- final MouseCursorSession lastSession = _lastSession[device];
+ final MouseCursorSession? lastSession = _lastSession[device];
final MouseCursor nextCursor = _findFirstCursor(details.nextAnnotations.keys);
if (lastSession?.cursor == nextCursor)
return;
@@ -273,7 +271,7 @@
String get debugDescription => 'defer';
/// Returns the first cursor that is not a [MouseCursor.defer].
- static MouseCursor firstNonDeferred(Iterable<MouseCursor> cursors) {
+ static MouseCursor? firstNonDeferred(Iterable<MouseCursor> cursors) {
for (final MouseCursor cursor in cursors) {
assert(cursor != null);
if (cursor != MouseCursor.defer)
@@ -370,7 +368,7 @@
// Application code shouldn't directly instantiate system mouse cursors, since
// the supported system cursors are enumerated in [SystemMouseCursors].
const SystemMouseCursor._({
- @required this.kind,
+ required this.kind,
}) : assert(kind != null);
/// A string that identifies the kind of the cursor.
@@ -386,7 +384,7 @@
_SystemMouseCursorSession createSession(int device) => _SystemMouseCursorSession(this, device);
@override
- bool operator ==(dynamic other) {
+ bool operator ==(Object other) {
if (other.runtimeType != runtimeType)
return false;
return other is SystemMouseCursor
@@ -419,7 +417,7 @@
class SystemMouseCursors {
// This class only contains static members, and should not be instantiated or
// extended.
- factory SystemMouseCursors._() => null;
+ factory SystemMouseCursors._() => throw Error();
// The mapping in this class must be kept in sync with the following files in
// the engine:
@@ -438,7 +436,7 @@
static const SystemMouseCursor none = SystemMouseCursor._(kind: 'none');
- //// STATUS ////
+ // STATUS
/// The platform-dependent basic cursor.
///
@@ -550,7 +548,7 @@
static const SystemMouseCursor help = SystemMouseCursor._(kind: 'help');
- //// SELECTION ////
+ // SELECTION
/// A cursor indicating selectable text.
///
@@ -604,7 +602,7 @@
static const SystemMouseCursor precise = SystemMouseCursor._(kind: 'precise');
- //// DRAG-AND-DROP ////
+ // DRAG-AND-DROP
/// A cursor indicating moving something.
///
@@ -696,7 +694,7 @@
static const SystemMouseCursor disappearing = SystemMouseCursor._(kind: 'disappearing');
- //// RESIZING AND SCROLLING ////
+ // RESIZING AND SCROLLING
/// A cursor indicating scrolling in any direction.
///
@@ -897,7 +895,7 @@
static const SystemMouseCursor resizeRow = SystemMouseCursor._(kind: 'resizeRow');
- //// OTHER OPERATIONS ////
+ // OTHER OPERATIONS
/// A cursor indicating zooming in.
///
diff --git a/packages/flutter/lib/src/rendering/mouse_tracking.dart b/packages/flutter/lib/src/rendering/mouse_tracking.dart
index 23ec3da..03ed7e5 100644
--- a/packages/flutter/lib/src/rendering/mouse_tracking.dart
+++ b/packages/flutter/lib/src/rendering/mouse_tracking.dart
@@ -2,8 +2,6 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-// @dart = 2.8
-
import 'dart:collection' show LinkedHashMap;
import 'dart:ui';
@@ -72,7 +70,7 @@
///
/// * [onExit], which is triggered when a mouse pointer exits the region.
/// * [MouseRegion.onEnter], which uses this callback.
- final PointerEnterEventListener onEnter;
+ final PointerEnterEventListener? onEnter;
/// Triggered when a mouse pointer has moved onto or within the region without
/// buttons pressed.
@@ -82,7 +80,7 @@
/// See also:
///
/// * [MouseRegion.onHover], which uses this callback.
- final PointerHoverEventListener onHover;
+ final PointerHoverEventListener? onHover;
/// Triggered when a mouse pointer, with or without buttons pressed, has
/// exited the region.
@@ -97,7 +95,7 @@
/// * [onEnter], which is triggered when a mouse pointer enters the region.
/// * [MouseRegion.onExit], which uses this callback, but is not triggered in
/// certain cases and does not always match its earlier [MouseRegion.onEnter].
- final PointerExitEventListener onExit;
+ final PointerExitEventListener? onExit;
/// The mouse cursor for mouse pointers that are hovering over the region.
///
@@ -116,9 +114,9 @@
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
- properties.add(FlagsSummary<Function>(
+ properties.add(FlagsSummary<Function?>(
'callbacks',
- <String, Function> {
+ <String, Function?> {
'enter': onEnter,
'exit': onExit,
},
@@ -137,7 +135,7 @@
// Various states of a connected mouse device used by [BaseMouseTracker].
class _MouseState {
_MouseState({
- @required PointerEvent initialEvent,
+ required PointerEvent initialEvent,
}) : assert(initialEvent != null),
_latestEvent = initialEvent;
@@ -170,10 +168,7 @@
@override
String toString() {
- String describeEvent(PointerEvent event) {
- return event == null ? 'null' : describeIdentity(event);
- }
- final String describeLatestEvent = 'latestEvent: ${describeEvent(latestEvent)}';
+ final String describeLatestEvent = 'latestEvent: ${describeIdentity(latestEvent)}';
final String describeAnnotations = 'annotations: [list of ${annotations.length}]';
return '${describeIdentity(this)}($describeLatestEvent, $describeAnnotations)';
}
@@ -191,9 +186,9 @@
///
/// All parameters are required.
const MouseTrackerUpdateDetails.byNewFrame({
- @required this.lastAnnotations,
- @required this.nextAnnotations,
- @required this.previousEvent,
+ required this.lastAnnotations,
+ required this.nextAnnotations,
+ required this.previousEvent,
}) : assert(previousEvent != null),
assert(lastAnnotations != null),
assert(nextAnnotations != null),
@@ -204,10 +199,10 @@
/// The [lastAnnotations], [nextAnnotations], and [triggeringEvent] are
/// required.
const MouseTrackerUpdateDetails.byPointerEvent({
- @required this.lastAnnotations,
- @required this.nextAnnotations,
+ required this.lastAnnotations,
+ required this.nextAnnotations,
this.previousEvent,
- @required this.triggeringEvent,
+ required PointerEvent this.triggeringEvent,
}) : assert(triggeringEvent != null),
assert(lastAnnotations != null),
assert(nextAnnotations != null);
@@ -230,16 +225,16 @@
/// If the update is triggered by a pointer event, the [previousEvent] is not
/// null except for cases where the event is the first event observed by the
/// pointer (which is not necessarily a [PointerAddedEvent]).
- final PointerEvent previousEvent;
+ final PointerEvent? previousEvent;
/// The event that triggered this update.
///
/// It is non-null if and only if the update is triggered by a pointer event.
- final PointerEvent triggeringEvent;
+ final PointerEvent? triggeringEvent;
/// The pointing device of this update.
int get device {
- final int result = (previousEvent ?? triggeringEvent).device;
+ final int result = (previousEvent ?? triggeringEvent)!.device;
assert(result != null);
return result;
}
@@ -248,7 +243,7 @@
///
/// The [latestEvent] is never null.
PointerEvent get latestEvent {
- final PointerEvent result = triggeringEvent ?? previousEvent;
+ final PointerEvent result = triggeringEvent ?? previousEvent!;
assert(result != null);
return result;
}
@@ -327,7 +322,7 @@
}
// Whether an observed event might update a device.
- static bool _shouldMarkStateDirty(_MouseState state, PointerEvent event) {
+ static bool _shouldMarkStateDirty(_MouseState? state, PointerEvent event) {
if (state == null)
return true;
assert(event != null);
@@ -351,7 +346,7 @@
as LinkedHashMap<MouseTrackerAnnotation, Matrix4>;
for (final HitTestEntry entry in result.path) {
if (entry.target is MouseTrackerAnnotation) {
- annotations[entry.target as MouseTrackerAnnotation] = entry.transform;
+ annotations[entry.target as MouseTrackerAnnotation] = entry.transform!;
}
}
return annotations;
@@ -416,7 +411,7 @@
if (event is PointerSignalEvent)
return;
final int device = event.device;
- final _MouseState existingState = _mouseStates[device];
+ final _MouseState? existingState = _mouseStates[device];
if (!_shouldMarkStateDirty(existingState, event))
return;
@@ -433,7 +428,7 @@
if (event is PointerRemovedEvent)
_mouseStates.remove(event.device);
}
- final _MouseState targetState = _mouseStates[device] ?? existingState;
+ final _MouseState targetState = _mouseStates[device] ?? existingState!;
final PointerEvent lastEvent = targetState.replaceLatestEvent(event);
final LinkedHashMap<MouseTrackerAnnotation, Matrix4> nextAnnotations = event is PointerRemovedEvent ?
@@ -487,8 +482,8 @@
mixin _MouseTrackerEventMixin on BaseMouseTracker {
// Handles device update and dispatches mouse event callbacks.
static void _handleDeviceUpdateMouseEvents(MouseTrackerUpdateDetails details) {
- final PointerEvent previousEvent = details.previousEvent;
- final PointerEvent triggeringEvent = details.triggeringEvent;
+ final PointerEvent? previousEvent = details.previousEvent;
+ final PointerEvent? triggeringEvent = details.triggeringEvent;
final PointerEvent latestEvent = details.latestEvent;
final LinkedHashMap<MouseTrackerAnnotation, Matrix4> lastAnnotations = details.lastAnnotations;
@@ -506,7 +501,7 @@
lastAnnotations.forEach((MouseTrackerAnnotation annotation, Matrix4 transform) {
if (!nextAnnotations.containsKey(annotation))
if (annotation.onExit != null)
- annotation.onExit(baseExitEvent.transformed(lastAnnotations[annotation]));
+ annotation.onExit!(baseExitEvent.transformed(lastAnnotations[annotation]));
});
// Send enter events to annotations that are not in last but in next, in
@@ -517,14 +512,14 @@
final PointerEnterEvent baseEnterEvent = PointerEnterEvent.fromMouseEvent(latestEvent);
for (final MouseTrackerAnnotation annotation in enteringAnnotations.reversed) {
if (annotation.onEnter != null)
- annotation.onEnter(baseEnterEvent.transformed(nextAnnotations[annotation]));
+ annotation.onEnter!(baseEnterEvent.transformed(nextAnnotations[annotation]));
}
// Send hover events to annotations that are in next, in reverse visual
// order. The reverse visual order is chosen only because of the simplicity
// by keeping the hover events aligned with enter events.
if (triggeringEvent is PointerHoverEvent) {
- final Offset hoverPositionBeforeUpdate = previousEvent is PointerHoverEvent ? previousEvent.position : null;
+ final Offset? hoverPositionBeforeUpdate = previousEvent is PointerHoverEvent ? previousEvent.position : null;
final bool pointerHasMoved = hoverPositionBeforeUpdate == null || hoverPositionBeforeUpdate != triggeringEvent.position;
// If the hover event follows a non-hover event, or has moved since the
// last hover, then trigger the hover callback on all annotations.
@@ -533,7 +528,7 @@
final Iterable<MouseTrackerAnnotation> hoveringAnnotations = pointerHasMoved ? nextAnnotations.keys.toList().reversed : enteringAnnotations;
for (final MouseTrackerAnnotation annotation in hoveringAnnotations) {
if (annotation.onHover != null) {
- annotation.onHover(triggeringEvent.transformed(nextAnnotations[annotation]));
+ annotation.onHover!(triggeringEvent.transformed(nextAnnotations[annotation]));
}
}
}
diff --git a/packages/flutter/lib/src/rendering/object.dart b/packages/flutter/lib/src/rendering/object.dart
index 30bfc0c..db89240 100644
--- a/packages/flutter/lib/src/rendering/object.dart
+++ b/packages/flutter/lib/src/rendering/object.dart
@@ -2,8 +2,6 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-// @dart = 2.8
-
import 'dart:developer';
import 'dart:ui' as ui show PictureRecorder;
@@ -108,7 +106,7 @@
static void _repaintCompositedChild(
RenderObject child, {
bool debugAlsoPaintedParent = false,
- PaintingContext childContext,
+ PaintingContext? childContext,
}) {
assert(child.isRepaintBoundary);
assert(() {
@@ -119,7 +117,7 @@
);
return true;
}());
- OffsetLayer childLayer = child._layer as OffsetLayer;
+ OffsetLayer? childLayer = child._layer as OffsetLayer?;
if (childLayer == null) {
assert(debugAlsoPaintedParent);
// Not using the `layer` setter because the setter asserts that we not
@@ -135,10 +133,10 @@
assert(identical(childLayer, child._layer));
assert(child._layer is OffsetLayer);
assert(() {
- child._layer.debugCreator = child.debugCreator ?? child.runtimeType;
+ child._layer!.debugCreator = child.debugCreator ?? child.runtimeType;
return true;
}());
- childContext ??= PaintingContext(child._layer, child.paintBounds);
+ childContext ??= PaintingContext(child._layer!, child.paintBounds);
child._paintWithContext(childContext, Offset.zero);
// Double-check that the paint method did not replace the layer (the first
@@ -158,7 +156,7 @@
static void debugInstrumentRepaintCompositedChild(
RenderObject child, {
bool debugAlsoPaintedParent = false,
- @required PaintingContext customContext,
+ required PaintingContext customContext,
}) {
assert(() {
_repaintCompositedChild(
@@ -180,7 +178,7 @@
if (debugProfilePaintsEnabled)
Timeline.startSync('${child.runtimeType}', arguments: timelineArgumentsIndicatingLandmarkEvent);
if (debugOnProfilePaint != null)
- debugOnProfilePaint(child);
+ debugOnProfilePaint!(child);
return true;
}());
@@ -201,7 +199,7 @@
void _compositeChild(RenderObject child, Offset offset) {
assert(!_isRecording);
assert(child.isRepaintBoundary);
- assert(_canvas == null || _canvas.getSaveCount() == 1);
+ assert(_canvas == null || _canvas!.getSaveCount() == 1);
// Create a layer for our child, and paint the child into it.
if (child._needsPaint) {
@@ -213,14 +211,14 @@
includedParent: true,
includedChild: false,
);
- child._layer.debugCreator = child.debugCreator ?? child;
+ child._layer!.debugCreator = child.debugCreator ?? child;
return true;
}());
}
assert(child._layer is OffsetLayer);
final OffsetLayer childOffsetLayer = child._layer as OffsetLayer;
childOffsetLayer.offset = offset;
- appendLayer(child._layer);
+ appendLayer(child._layer!);
}
/// Adds a layer to the recording requiring that the recording is already
@@ -257,9 +255,9 @@
}
// Recording state
- PictureLayer _currentLayer;
- ui.PictureRecorder _recorder;
- Canvas _canvas;
+ PictureLayer? _currentLayer;
+ ui.PictureRecorder? _recorder;
+ Canvas? _canvas;
/// The canvas on which to paint.
///
@@ -270,15 +268,15 @@
Canvas get canvas {
if (_canvas == null)
_startRecording();
- return _canvas;
+ return _canvas!;
}
void _startRecording() {
assert(!_isRecording);
_currentLayer = PictureLayer(estimatedBounds);
_recorder = ui.PictureRecorder();
- _canvas = Canvas(_recorder);
- _containerLayer.append(_currentLayer);
+ _canvas = Canvas(_recorder!);
+ _containerLayer.append(_currentLayer!);
}
/// Stop recording to a canvas if recording has started.
@@ -313,7 +311,7 @@
}
return true;
}());
- _currentLayer.picture = _recorder.endRecording();
+ _currentLayer!.picture = _recorder!.endRecording();
_currentLayer = null;
_recorder = null;
_canvas = null;
@@ -385,7 +383,7 @@
///
/// * [addLayer], for pushing a layer without painting further contents
/// within it.
- void pushLayer(ContainerLayer childLayer, PaintingContextCallback painter, Offset offset, { Rect childPaintBounds }) {
+ void pushLayer(ContainerLayer childLayer, PaintingContextCallback painter, Offset offset, { Rect? childPaintBounds }) {
assert(painter != null);
// If a layer is being reused, it may already contain children. We remove
// them so that `painter` can add children that are relevant for this frame.
@@ -444,7 +442,7 @@
/// compositing) or until the render object changes the type of the layer
/// (e.g. from opacity layer to a clip rect layer).
/// {@endtemplate}
- ClipRectLayer pushClipRect(bool needsCompositing, Offset offset, Rect clipRect, PaintingContextCallback painter, { Clip clipBehavior = Clip.hardEdge, ClipRectLayer oldLayer }) {
+ ClipRectLayer? pushClipRect(bool needsCompositing, Offset offset, Rect clipRect, PaintingContextCallback painter, { Clip clipBehavior = Clip.hardEdge, ClipRectLayer? oldLayer }) {
final Rect offsetClipRect = clipRect.shift(offset);
if (needsCompositing) {
final ClipRectLayer layer = oldLayer ?? ClipRectLayer();
@@ -478,7 +476,7 @@
/// The `clipBehavior` argument controls how the rounded rectangle is clipped.
///
/// {@macro flutter.rendering.object.oldLayer}
- ClipRRectLayer pushClipRRect(bool needsCompositing, Offset offset, Rect bounds, RRect clipRRect, PaintingContextCallback painter, { Clip clipBehavior = Clip.antiAlias, ClipRRectLayer oldLayer }) {
+ ClipRRectLayer? pushClipRRect(bool needsCompositing, Offset offset, Rect bounds, RRect clipRRect, PaintingContextCallback painter, { Clip clipBehavior = Clip.antiAlias, ClipRRectLayer? oldLayer }) {
assert(clipBehavior != null);
final Rect offsetBounds = bounds.shift(offset);
final RRect offsetClipRRect = clipRRect.shift(offset);
@@ -514,7 +512,7 @@
/// The `clipBehavior` argument controls how the path is clipped.
///
/// {@macro flutter.rendering.object.oldLayer}
- ClipPathLayer pushClipPath(bool needsCompositing, Offset offset, Rect bounds, Path clipPath, PaintingContextCallback painter, { Clip clipBehavior = Clip.antiAlias, ClipPathLayer oldLayer }) {
+ ClipPathLayer? pushClipPath(bool needsCompositing, Offset offset, Rect bounds, Path clipPath, PaintingContextCallback painter, { Clip clipBehavior = Clip.antiAlias, ClipPathLayer? oldLayer }) {
assert(clipBehavior != null);
final Rect offsetBounds = bounds.shift(offset);
final Path offsetClipPath = clipPath.shift(offset);
@@ -547,7 +545,7 @@
/// [RenderObject.alwaysNeedsCompositing] property to return true. That informs
/// ancestor render objects that this render object will include a composited
/// layer, which, for example, causes them to use composited clips.
- ColorFilterLayer pushColorFilter(Offset offset, ColorFilter colorFilter, PaintingContextCallback painter, { ColorFilterLayer oldLayer }) {
+ ColorFilterLayer pushColorFilter(Offset offset, ColorFilter colorFilter, PaintingContextCallback painter, { ColorFilterLayer? oldLayer }) {
assert(colorFilter != null);
final ColorFilterLayer layer = oldLayer ?? ColorFilterLayer();
layer.colorFilter = colorFilter;
@@ -570,7 +568,7 @@
/// is called synchronously during the call to [pushTransform].
///
/// {@macro flutter.rendering.object.oldLayer}
- TransformLayer pushTransform(bool needsCompositing, Offset offset, Matrix4 transform, PaintingContextCallback painter, { TransformLayer oldLayer }) {
+ TransformLayer? pushTransform(bool needsCompositing, Offset offset, Matrix4 transform, PaintingContextCallback painter, { TransformLayer? oldLayer }) {
final Matrix4 effectiveTransform = Matrix4.translationValues(offset.dx, offset.dy, 0.0)
..multiply(transform)..translate(-offset.dx, -offset.dy);
if (needsCompositing) {
@@ -611,7 +609,7 @@
/// [RenderObject.alwaysNeedsCompositing] property to return true. That informs
/// ancestor render objects that this render object will include a composited
/// layer, which, for example, causes them to use composited clips.
- OpacityLayer pushOpacity(Offset offset, int alpha, PaintingContextCallback painter, { OpacityLayer oldLayer }) {
+ OpacityLayer pushOpacity(Offset offset, int alpha, PaintingContextCallback painter, { OpacityLayer? oldLayer }) {
final OpacityLayer layer = oldLayer ?? OpacityLayer();
layer
..alpha = alpha
@@ -705,7 +703,7 @@
/// Returns the same as [isNormalized] if asserts are disabled.
bool debugAssertIsValid({
bool isAppliedConstraint = false,
- InformationCollector informationCollector,
+ InformationCollector? informationCollector,
}) {
assert(isNormalized);
return isNormalized;
@@ -741,16 +739,17 @@
/// [PipelineOwner] for the render tree from which you wish to read semantics.
/// You can obtain the [PipelineOwner] using the [RenderObject.owner] property.
class SemanticsHandle {
- SemanticsHandle._(this._owner, this.listener)
- : assert(_owner != null) {
+ SemanticsHandle._(PipelineOwner owner, this.listener)
+ : assert(owner != null),
+ _owner = owner {
if (listener != null)
- _owner.semanticsOwner.addListener(listener);
+ _owner.semanticsOwner!.addListener(listener!);
}
- PipelineOwner _owner;
+ final PipelineOwner _owner;
/// The callback that will be notified when the semantics tree updates.
- final VoidCallback listener;
+ final VoidCallback? listener;
/// Closes the semantics handle and stops calling [listener] when the
/// semantics updates.
@@ -760,21 +759,9 @@
/// semantics tree.
@mustCallSuper
void dispose() {
- assert(() {
- if (_owner == null) {
- throw FlutterError(
- 'SemanticsHandle has already been disposed.\n'
- 'Each SemanticsHandle should be disposed exactly once.'
- );
- }
- return true;
- }());
- if (_owner != null) {
- if (listener != null)
- _owner.semanticsOwner.removeListener(listener);
- _owner._didDisposeSemanticsHandle();
- _owner = null;
- }
+ if (listener != null)
+ _owner.semanticsOwner!.removeListener(listener!);
+ _owner._didDisposeSemanticsHandle();
}
}
@@ -826,18 +813,18 @@
/// various stages of the pipeline. This function might be called multiple
/// times in quick succession. Implementations should take care to discard
/// duplicate calls quickly.
- final VoidCallback onNeedVisualUpdate;
+ final VoidCallback? onNeedVisualUpdate;
/// Called whenever this pipeline owner creates a semantics object.
///
/// Typical implementations will schedule the creation of the initial
/// semantics tree.
- final VoidCallback onSemanticsOwnerCreated;
+ final VoidCallback? onSemanticsOwnerCreated;
/// Called whenever this pipeline owner disposes its semantics owner.
///
/// Typical implementations will tear down the semantics tree.
- final VoidCallback onSemanticsOwnerDisposed;
+ final VoidCallback? onSemanticsOwnerDisposed;
/// Calls [onNeedVisualUpdate] if [onNeedVisualUpdate] is not null.
///
@@ -845,15 +832,15 @@
/// to update its visual appearance.
void requestVisualUpdate() {
if (onNeedVisualUpdate != null)
- onNeedVisualUpdate();
+ onNeedVisualUpdate!();
}
/// The unique object managed by this pipeline that has no parent.
///
/// This object does not have to be a [RenderObject].
- AbstractNode get rootNode => _rootNode;
- AbstractNode _rootNode;
- set rootNode(AbstractNode value) {
+ AbstractNode? get rootNode => _rootNode;
+ AbstractNode? _rootNode;
+ set rootNode(AbstractNode? value) {
if (_rootNode == value)
return;
_rootNode?.detach();
@@ -867,7 +854,8 @@
///
/// Specifically, whether [flushLayout] is currently running.
///
- /// Only valid when asserts are enabled.
+ /// Only valid when asserts are enabled; in release builds, this
+ /// always returns false.
bool get debugDoingLayout => _debugDoingLayout;
bool _debugDoingLayout = false;
@@ -917,7 +905,7 @@
// See [RenderObject.invokeLayoutCallback].
void _enableMutationsToDirtySubtrees(VoidCallback callback) {
assert(_debugDoingLayout);
- bool oldState;
+ bool? oldState;
assert(() {
oldState = _debugAllowMutationsToDirtySubtrees;
_debugAllowMutationsToDirtySubtrees = true;
@@ -927,7 +915,7 @@
callback();
} finally {
assert(() {
- _debugAllowMutationsToDirtySubtrees = oldState;
+ _debugAllowMutationsToDirtySubtrees = oldState!;
return true;
}());
}
@@ -959,7 +947,8 @@
///
/// Specifically, whether [flushPaint] is currently running.
///
- /// Only valid when asserts are enabled.
+ /// Only valid when asserts are enabled. In release builds,
+ /// this always returns false.
bool get debugDoingPaint => _debugDoingPaint;
bool _debugDoingPaint = false;
@@ -985,7 +974,7 @@
for (final RenderObject node in dirtyNodes..sort((RenderObject a, RenderObject b) => b.depth - a.depth)) {
assert(node._layer != null);
if (node._needsPaint && node.owner == this) {
- if (node._layer.attached) {
+ if (node._layer!.attached) {
PaintingContext.repaintCompositedChild(node);
} else {
node._skippedPaintingOnLayer();
@@ -1014,8 +1003,8 @@
///
/// When [semanticsOwner] is null, the [PipelineOwner] skips all steps
/// relating to semantics.
- SemanticsOwner get semanticsOwner => _semanticsOwner;
- SemanticsOwner _semanticsOwner;
+ SemanticsOwner? get semanticsOwner => _semanticsOwner;
+ SemanticsOwner? _semanticsOwner;
/// The number of clients registered to listen for semantics.
///
@@ -1036,13 +1025,13 @@
/// [SemanticsHandle.dispose]. Once all the outstanding [SemanticsHandle]
/// objects for a given [PipelineOwner] are closed, the [PipelineOwner] stops
/// maintaining the semantics tree.
- SemanticsHandle ensureSemantics({ VoidCallback listener }) {
+ SemanticsHandle ensureSemantics({ VoidCallback? listener }) {
_outstandingSemanticsHandles += 1;
if (_outstandingSemanticsHandles == 1) {
assert(_semanticsOwner == null);
_semanticsOwner = SemanticsOwner();
if (onSemanticsOwnerCreated != null)
- onSemanticsOwnerCreated();
+ onSemanticsOwnerCreated!();
}
return SemanticsHandle._(this, listener);
}
@@ -1051,10 +1040,10 @@
assert(_semanticsOwner != null);
_outstandingSemanticsHandles -= 1;
if (_outstandingSemanticsHandles == 0) {
- _semanticsOwner.dispose();
+ _semanticsOwner!.dispose();
_semanticsOwner = null;
if (onSemanticsOwnerDisposed != null)
- onSemanticsOwnerDisposed();
+ onSemanticsOwnerDisposed!();
}
}
@@ -1091,7 +1080,7 @@
if (node._needsSemanticsUpdate && node.owner == this)
node._updateSemantics();
}
- _semanticsOwner.sendSemanticsUpdate();
+ _semanticsOwner!.sendSemanticsUpdate();
} finally {
assert(_nodesNeedingSemantics.isEmpty);
assert(() {
@@ -1263,7 +1252,7 @@
/// used between the parent and child. For example, in box layout, the
/// parent data is completely opaque but in sector layout the child is
/// permitted to read some fields of the parent data.
- ParentData parentData;
+ ParentData? parentData;
/// Override to setup parent data correctly for your children.
///
@@ -1300,7 +1289,7 @@
assert(child != null);
assert(child.parentData != null);
child._cleanRelayoutBoundary();
- child.parentData.detach();
+ child.parentData!.detach();
child.parentData = null;
super.dropChild(child);
markNeedsLayout();
@@ -1316,7 +1305,7 @@
/// The object responsible for creating this render object.
///
/// Used in debug messages.
- dynamic debugCreator;
+ Object? debugCreator;
void _debugReportException(String method, dynamic exception, StackTrace stack) {
FlutterError.reportError(FlutterErrorDetails(
@@ -1326,7 +1315,7 @@
context: ErrorDescription('during $method()'),
informationCollector: () sync* {
if (debugCreator != null)
- yield DiagnosticsDebugCreator(debugCreator);
+ yield DiagnosticsDebugCreator(debugCreator!);
yield describeForError('The following RenderObject was being processed when the exception was fired');
// TODO(jacobr): this error message has a code smell. Consider whether
// displaying the truncated children is really useful for command line
@@ -1355,18 +1344,17 @@
///
/// Only valid when asserts are enabled. In release builds, always returns
/// null.
- static RenderObject get debugActiveLayout => _debugActiveLayout;
- static RenderObject _debugActiveLayout;
+ static RenderObject? get debugActiveLayout => _debugActiveLayout;
+ static RenderObject? _debugActiveLayout;
/// Whether the parent render object is permitted to use this render object's
/// size.
///
/// Determined by the `parentUsesSize` parameter to [layout].
///
- /// Only valid when asserts are enabled. In release builds, always returns
- /// null.
- bool get debugCanParentUseSize => _debugCanParentUseSize;
- bool _debugCanParentUseSize;
+ /// Only valid when asserts are enabled. In release builds, throws.
+ bool get debugCanParentUseSize => _debugCanParentUseSize!;
+ bool? _debugCanParentUseSize;
bool _debugMutationsLocked = false;
@@ -1375,7 +1363,7 @@
/// Only valid when asserts are enabled. In release builds, always returns
/// null.
bool get _debugCanPerformMutations {
- bool result;
+ late bool result;
assert(() {
RenderObject node = this;
while (true) {
@@ -1383,7 +1371,7 @@
result = true;
break;
}
- if (owner != null && owner._debugAllowMutationsToDirtySubtrees && node._needsLayout) {
+ if (owner != null && owner!._debugAllowMutationsToDirtySubtrees && node._needsLayout) {
result = true;
break;
}
@@ -1403,7 +1391,7 @@
}
@override
- PipelineOwner get owner => super.owner as PipelineOwner;
+ PipelineOwner? get owner => super.owner as PipelineOwner?;
@override
void attach(PipelineOwner owner) {
@@ -1439,11 +1427,11 @@
/// This is only set in debug mode. In general, render objects should not need
/// to condition their runtime behavior on whether they are dirty or not,
/// since they should only be marked dirty immediately prior to being laid
- /// out and painted.
+ /// out and painted. In release builds, this throws.
///
/// It is intended to be used by tests and asserts.
bool get debugNeedsLayout {
- bool result;
+ late bool result;
assert(() {
result = _needsLayout;
return true;
@@ -1452,7 +1440,7 @@
}
bool _needsLayout = true;
- RenderObject _relayoutBoundary;
+ RenderObject? _relayoutBoundary;
bool _doingThisLayoutWithCallback = false;
/// The layout constraints most recently supplied by the parent.
@@ -1460,12 +1448,12 @@
/// If layout has not yet happened, accessing this getter will
/// throw a [StateError] exception.
@protected
- Constraints/*!*/ get constraints {
+ Constraints get constraints {
if (_constraints == null)
throw StateError('A RenderObject does not have any constraints before it has been laid out.');
- return _constraints/*!*/;
+ return _constraints!;
}
- Constraints _constraints;
+ Constraints? _constraints;
/// Verify that the object's constraints are being met. Override
/// this function in a subclass to verify that your state matches
@@ -1555,8 +1543,8 @@
debugPrintStack(label: 'markNeedsLayout() called for $this');
return true;
}());
- owner._nodesNeedingLayout.add(this);
- owner.requestVisualUpdate();
+ owner!._nodesNeedingLayout.add(this);
+ owner!.requestVisualUpdate();
}
}
}
@@ -1573,7 +1561,8 @@
@protected
void markParentNeedsLayout() {
_needsLayout = true;
- final RenderObject parent = this.parent as RenderObject;
+ assert(this.parent != null);
+ final RenderObject parent = this.parent! as RenderObject;
if (!_doingThisLayoutWithCallback) {
parent.markNeedsLayout();
} else {
@@ -1616,19 +1605,19 @@
void scheduleInitialLayout() {
assert(attached);
assert(parent is! RenderObject);
- assert(!owner._debugDoingLayout);
+ assert(!owner!._debugDoingLayout);
assert(_relayoutBoundary == null);
_relayoutBoundary = this;
assert(() {
_debugCanParentUseSize = false;
return true;
}());
- owner._nodesNeedingLayout.add(this);
+ owner!._nodesNeedingLayout.add(this);
}
void _layoutWithoutResize() {
assert(_relayoutBoundary == this);
- RenderObject debugPreviousActiveLayout;
+ RenderObject? debugPreviousActiveLayout;
assert(!_debugMutationsLocked);
assert(!_doingThisLayoutWithCallback);
assert(_debugCanParentUseSize != null);
@@ -1689,7 +1678,7 @@
isAppliedConstraint: true,
informationCollector: () sync* {
final List<String> stack = StackTrace.current.toString().split('\n');
- int targetFrame;
+ int? targetFrame;
final Pattern layoutFramePattern = RegExp(r'^#[0-9]+ +RenderObject.layout \(');
for (int i = 0; i < stack.length; i += 1) {
if (layoutFramePattern.matchAsPrefix(stack[i]) != null) {
@@ -1699,8 +1688,8 @@
}
if (targetFrame != null && targetFrame < stack.length) {
final Pattern targetFramePattern = RegExp(r'^#[0-9]+ +(.+)$');
- final Match targetFrameMatch = targetFramePattern.matchAsPrefix(stack[targetFrame]);
- final String problemFunction = (targetFrameMatch != null && targetFrameMatch.groupCount > 0) ? targetFrameMatch.group(1) : stack[targetFrame].trim();
+ final Match? targetFrameMatch = targetFramePattern.matchAsPrefix(stack[targetFrame]);
+ final String? problemFunction = (targetFrameMatch != null && targetFrameMatch.groupCount > 0) ? targetFrameMatch.group(1) : stack[targetFrame].trim();
// TODO(jacobr): this case is similar to displaying a single stack frame.
yield ErrorDescription(
"These invalid constraints were provided to $runtimeType's layout() "
@@ -1713,7 +1702,7 @@
));
assert(!_debugDoingThisResize);
assert(!_debugDoingThisLayout);
- RenderObject relayoutBoundary;
+ RenderObject? relayoutBoundary;
if (!parentUsesSize || sizedByParent || constraints.isTight || parent is! RenderObject) {
relayoutBoundary = this;
} else {
@@ -1729,7 +1718,7 @@
// to itself, so it has the right internal debug values.
_debugDoingThisResize = sizedByParent;
_debugDoingThisLayout = !sizedByParent;
- final RenderObject debugPreviousActiveLayout = _debugActiveLayout;
+ final RenderObject? debugPreviousActiveLayout = _debugActiveLayout;
_debugActiveLayout = this;
debugResetSize();
_debugActiveLayout = debugPreviousActiveLayout;
@@ -1777,7 +1766,7 @@
return true;
}());
}
- RenderObject debugPreviousActiveLayout;
+ RenderObject? debugPreviousActiveLayout;
assert(() {
_debugDoingThisLayout = true;
debugPreviousActiveLayout = _debugActiveLayout;
@@ -1891,7 +1880,7 @@
assert(!_doingThisLayoutWithCallback);
_doingThisLayoutWithCallback = true;
try {
- owner._enableMutationsToDirtySubtrees(() { callback(constraints as T); });
+ owner!._enableMutationsToDirtySubtrees(() { callback(constraints as T); });
} finally {
_doingThisLayoutWithCallback = false;
}
@@ -1899,9 +1888,9 @@
/// Rotate this render object (not yet implemented).
void rotate({
- int oldAngle, // 0..3
- int newAngle, // 0..3
- Duration time,
+ int? oldAngle, // 0..3
+ int? newAngle, // 0..3
+ Duration? time,
}) { }
// when the parent has rotated (e.g. when the screen has been turned
@@ -1928,8 +1917,8 @@
///
/// Only valid when asserts are enabled. In release builds, always returns
/// null.
- static RenderObject get debugActivePaint => _debugActivePaint;
- static RenderObject _debugActivePaint;
+ static RenderObject? get debugActivePaint => _debugActivePaint;
+ static RenderObject? _debugActivePaint;
/// Whether this render object repaints separately from its parent.
///
@@ -1985,13 +1974,13 @@
/// [paint] method. The [paint] method must not replace the value of this
/// field.
@protected
- ContainerLayer get layer {
+ ContainerLayer? get layer {
assert(!isRepaintBoundary || (_layer == null || _layer is OffsetLayer));
return _layer;
}
@protected
- set layer(ContainerLayer newLayer) {
+ set layer(ContainerLayer? newLayer) {
assert(
!isRepaintBoundary,
'Attempted to set a layer to a repaint boundary render object.\n'
@@ -2000,7 +1989,7 @@
);
_layer = newLayer;
}
- ContainerLayer _layer;
+ ContainerLayer? _layer;
/// In debug mode, the compositing layer that this render object uses to repaint.
///
@@ -2009,8 +1998,8 @@
/// is dirty.
///
/// For production code, consider [layer].
- ContainerLayer get debugLayer {
- ContainerLayer result;
+ ContainerLayer? get debugLayer {
+ ContainerLayer? result;
assert(() {
result = _layer;
return true;
@@ -2049,17 +2038,17 @@
}
}
assert(() {
- final AbstractNode parent = this.parent;
+ final AbstractNode? parent = this.parent;
if (parent is RenderObject)
return parent._needsCompositing;
return true;
}());
// parent is fine (or there isn't one), but we are dirty
if (owner != null)
- owner._nodesNeedingCompositingBitsUpdate.add(this);
+ owner!._nodesNeedingCompositingBitsUpdate.add(this);
}
- bool _needsCompositing; // initialized in the constructor
+ late bool _needsCompositing; // initialized in the constructor
/// Whether we or one of our descendants has a compositing layer.
///
/// If this node needs compositing as indicated by this bit, then all ancestor
@@ -2094,7 +2083,7 @@
/// This is only set in debug mode. In general, render objects should not need
/// to condition their runtime behavior on whether they are dirty or not,
/// since they should only be marked dirty immediately prior to being laid
- /// out and painted.
+ /// out and painted. (In release builds, this throws.)
///
/// It is intended to be used by tests and asserts.
///
@@ -2104,7 +2093,7 @@
/// [markNeedsPaint] method is implicitly called by the framework after a
/// render object is laid out, prior to the paint phase.
bool get debugNeedsPaint {
- bool result;
+ late bool result;
assert(() {
result = _needsPaint;
return true;
@@ -2134,7 +2123,7 @@
/// layer, thus limiting the number of nodes that [markNeedsPaint] must mark
/// dirty.
void markNeedsPaint() {
- assert(owner == null || !owner.debugDoingPaint);
+ assert(owner == null || !owner!.debugDoingPaint);
if (_needsPaint)
return;
_needsPaint = true;
@@ -2148,8 +2137,8 @@
// ourselves without involving any other nodes.
assert(_layer is OffsetLayer);
if (owner != null) {
- owner._nodesNeedingPaint.add(this);
- owner.requestVisualUpdate();
+ owner!._nodesNeedingPaint.add(this);
+ owner!.requestVisualUpdate();
}
} else if (parent is RenderObject) {
final RenderObject parent = this.parent as RenderObject;
@@ -2166,7 +2155,7 @@
// us. We don't add ourselves to _nodesNeedingPaint in this
// case, because the root is always told to paint regardless.
if (owner != null)
- owner.requestVisualUpdate();
+ owner!.requestVisualUpdate();
}
}
@@ -2180,18 +2169,17 @@
assert(isRepaintBoundary);
assert(_needsPaint);
assert(_layer != null);
- assert(!_layer.attached);
- AbstractNode ancestor = parent;
- while (ancestor is RenderObject) {
- final RenderObject node = ancestor as RenderObject;
+ assert(!_layer!.attached);
+ AbstractNode? node = parent;
+ while (node is RenderObject) {
if (node.isRepaintBoundary) {
if (node._layer == null)
break; // looks like the subtree here has never been painted. let it handle itself.
- if (node._layer.attached)
+ if (node._layer!.attached)
break; // it's the one that detached us, so it's the one that will decide to repaint us.
node._needsPaint = true;
}
- ancestor = node.parent;
+ node = node.parent;
}
}
@@ -2205,12 +2193,12 @@
assert(rootLayer.attached);
assert(attached);
assert(parent is! RenderObject);
- assert(!owner._debugDoingPaint);
+ assert(!owner!._debugDoingPaint);
assert(isRepaintBoundary);
assert(_layer == null);
_layer = rootLayer;
assert(_needsPaint);
- owner._nodesNeedingPaint.add(this);
+ owner!._nodesNeedingPaint.add(this);
}
/// Replace the layer. This is only valid for the root of a render
@@ -2222,10 +2210,10 @@
assert(rootLayer.attached);
assert(attached);
assert(parent is! RenderObject);
- assert(!owner._debugDoingPaint);
+ assert(!owner!._debugDoingPaint);
assert(isRepaintBoundary);
assert(_layer != null); // use scheduleInitialPaint the first time
- _layer.detach();
+ _layer!.detach();
_layer = rootLayer;
markNeedsPaint();
}
@@ -2310,7 +2298,7 @@
}
return true;
}());
- RenderObject debugLastActivePaint;
+ RenderObject? debugLastActivePaint;
assert(() {
_debugDoingThisPaint = true;
debugLastActivePaint = _debugActivePaint;
@@ -2384,11 +2372,11 @@
/// this means that this method maps to the global coordinate system in
/// logical pixels. To get physical pixels, use [applyPaintTransform] from the
/// [RenderView] to further transform the coordinate.
- Matrix4 getTransformTo(RenderObject ancestor) {
+ Matrix4 getTransformTo(RenderObject? ancestor) {
final bool ancestorSpecified = ancestor != null;
assert(attached);
if (ancestor == null) {
- final AbstractNode rootNode = owner.rootNode;
+ final AbstractNode? rootNode = owner!.rootNode;
if (rootNode is RenderObject)
ancestor = rootNode;
}
@@ -2398,7 +2386,7 @@
renderers.add(renderer);
}
if (ancestorSpecified)
- renderers.add(ancestor);
+ renderers.add(ancestor!);
final Matrix4 transform = Matrix4.identity();
for (int index = renderers.length - 1; index > 0; index -= 1) {
renderers[index].applyPaintTransform(renderers[index - 1], transform);
@@ -2415,7 +2403,7 @@
///
/// This is used in the semantics phase to avoid including children
/// that are not physically visible.
- Rect describeApproximatePaintClip(covariant RenderObject child) => null;
+ Rect? describeApproximatePaintClip(covariant RenderObject child) => null;
/// Returns a rect in this object's coordinate system that describes
/// which [SemanticsNode]s produced by the `child` should be included in the
@@ -2442,7 +2430,7 @@
///
/// * [RenderViewportBase.cacheExtent], used by viewports to extend their
/// semantics clip beyond their approximate paint clip.
- Rect describeSemanticsClip(covariant RenderObject child) => null;
+ Rect? describeSemanticsClip(covariant RenderObject? child) => null;
// SEMANTICS
@@ -2456,12 +2444,12 @@
void scheduleInitialSemantics() {
assert(attached);
assert(parent is! RenderObject);
- assert(!owner._debugDoingSemantics);
+ assert(!owner!._debugDoingSemantics);
assert(_semantics == null);
assert(_needsSemanticsUpdate);
- assert(owner._semanticsOwner != null);
- owner._nodesNeedingSemantics.add(this);
- owner.requestVisualUpdate();
+ assert(owner!._semanticsOwner != null);
+ owner!._nodesNeedingSemantics.add(this);
+ owner!.requestVisualUpdate();
}
/// Report the semantics of this node, for example for accessibility purposes.
@@ -2499,7 +2487,7 @@
/// ```
/// {@end-tool}
@protected
- void describeSemanticsConfiguration(SemanticsConfiguration/*!*/ config) {
+ void describeSemanticsConfiguration(SemanticsConfiguration config) {
// Nothing to do by default.
}
@@ -2512,10 +2500,10 @@
///
/// See [SemanticsNode.sendEvent] for a full description of the behavior.
void sendSemanticsEvent(SemanticsEvent semanticsEvent) {
- if (owner.semanticsOwner == null)
+ if (owner!.semanticsOwner == null)
return;
- if (_semantics != null && !_semantics.isMergedIntoParent) {
- _semantics.sendEvent(semanticsEvent);
+ if (_semantics != null && !_semantics!.isMergedIntoParent) {
+ _semantics!.sendEvent(semanticsEvent);
} else if (parent != null) {
final RenderObject renderParent = parent as RenderObject;
renderParent.sendSemanticsEvent(semanticsEvent);
@@ -2523,14 +2511,14 @@
}
// Use [_semanticsConfiguration] to access.
- SemanticsConfiguration _cachedSemanticsConfiguration;
+ SemanticsConfiguration? _cachedSemanticsConfiguration;
SemanticsConfiguration get _semanticsConfiguration {
if (_cachedSemanticsConfiguration == null) {
_cachedSemanticsConfiguration = SemanticsConfiguration();
- describeSemanticsConfiguration(_cachedSemanticsConfiguration);
+ describeSemanticsConfiguration(_cachedSemanticsConfiguration!);
}
- return _cachedSemanticsConfiguration;
+ return _cachedSemanticsConfiguration!;
}
/// The bounding box, in the local coordinate system, of this
@@ -2538,7 +2526,7 @@
Rect get semanticBounds;
bool _needsSemanticsUpdate = true;
- SemanticsNode _semantics;
+ SemanticsNode? _semantics;
/// The semantics of this render object.
///
@@ -2548,7 +2536,7 @@
///
/// Only valid in debug and profile mode. In release builds, always returns
/// null.
- SemanticsNode get debugSemantics {
+ SemanticsNode? get debugSemantics {
if (!kReleaseMode) {
return _semantics;
}
@@ -2576,8 +2564,8 @@
/// [RenderObject] as annotated by [describeSemanticsConfiguration] changes in
/// any way to update the semantics tree.
void markNeedsSemanticsUpdate() {
- assert(!attached || !owner._debugDoingSemantics);
- if (!attached || owner._semanticsOwner == null) {
+ assert(!attached || !owner!._debugDoingSemantics);
+ if (!attached || owner!._semanticsOwner == null) {
_cachedSemanticsConfiguration = null;
return;
}
@@ -2614,14 +2602,14 @@
// this block will ensure that the semantics of `this` node actually gets
// updated.
// (See semantics_10_test.dart for an example why this is required).
- owner._nodesNeedingSemantics.remove(this);
+ owner!._nodesNeedingSemantics.remove(this);
}
if (!node._needsSemanticsUpdate) {
node._needsSemanticsUpdate = true;
if (owner != null) {
assert(node._semanticsConfiguration.isSemanticBoundary || node.parent is! RenderObject);
- owner._nodesNeedingSemantics.add(node);
- owner.requestVisualUpdate();
+ owner!._nodesNeedingSemantics.add(node);
+ owner!.requestVisualUpdate();
}
}
}
@@ -2650,7 +2638,7 @@
/// Returns the semantics that this node would like to add to its parent.
_SemanticsFragment _getSemanticsForParent({
- @required bool mergeIntoParent,
+ required bool mergeIntoParent,
}) {
assert(mergeIntoParent != null);
assert(!_needsLayout, 'Updated layout information required for $this to calculate semantics.');
@@ -2702,7 +2690,7 @@
if (!config.isCompatibleWith(fragment.config))
toBeMarkedExplicit.add(fragment);
for (final _InterestingSemanticsFragment siblingFragment in fragments.sublist(0, fragments.length - 1)) {
- if (!fragment.config.isCompatibleWith(siblingFragment.config)) {
+ if (!fragment.config!.isCompatibleWith(siblingFragment.config)) {
toBeMarkedExplicit.add(fragment);
toBeMarkedExplicit.add(siblingFragment);
}
@@ -2818,9 +2806,9 @@
String header = describeIdentity(this);
if (_relayoutBoundary != null && _relayoutBoundary != this) {
int count = 1;
- RenderObject target = parent as RenderObject;
+ RenderObject? target = parent as RenderObject?;
while (target != null && target != _relayoutBoundary) {
- target = target.parent as RenderObject;
+ target = target.parent as RenderObject?;
count += 1;
}
header += ' relayoutBoundary=up$count';
@@ -2845,10 +2833,10 @@
@override
String toStringDeep({
String prefixLineOne = '',
- String prefixOtherLines = '',
+ String? prefixOtherLines = '',
DiagnosticLevel minLevel = DiagnosticLevel.debug,
}) {
- RenderObject debugPreviousActiveLayout;
+ RenderObject? debugPreviousActiveLayout;
assert(() {
debugPreviousActiveLayout = _debugActiveLayout;
_debugActiveLayout = null;
@@ -2876,7 +2864,7 @@
String joiner = ', ',
DiagnosticLevel minLevel = DiagnosticLevel.debug,
}) {
- RenderObject debugPreviousActiveLayout;
+ RenderObject? debugPreviousActiveLayout;
assert(() {
debugPreviousActiveLayout = _debugActiveLayout;
_debugActiveLayout = null;
@@ -2895,7 +2883,7 @@
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(FlagProperty('needsCompositing', value: _needsCompositing, ifTrue: 'needs compositing'));
- properties.add(DiagnosticsProperty<dynamic>('creator', debugCreator, defaultValue: null, level: DiagnosticLevel.debug));
+ properties.add(DiagnosticsProperty<Object?>('creator', debugCreator, defaultValue: null, level: DiagnosticLevel.debug));
properties.add(DiagnosticsProperty<ParentData>('parentData', parentData, tooltip: _debugCanParentUseSize == true ? 'can use size' : null, missingIfNull: true));
properties.add(DiagnosticsProperty<Constraints>('constraints', _constraints, missingIfNull: true));
// don't access it via the "layer" getter since that's only valid when we don't need paint
@@ -2933,8 +2921,8 @@
/// * [RenderViewportBase.showInViewport], which [RenderViewportBase] and
/// [SingleChildScrollView] delegate this method to.
void showOnScreen({
- RenderObject descendant,
- Rect rect,
+ RenderObject? descendant,
+ Rect? rect,
Duration duration = Duration.zero,
Curve curve = Curves.ease,
}) {
@@ -2993,13 +2981,13 @@
'a RenderSliver does not understand the RenderBox layout protocol.',
),
ErrorSpacer(),
- DiagnosticsProperty<dynamic>(
+ DiagnosticsProperty<Object?>(
'The $runtimeType that expected a $ChildType child was created by',
debugCreator,
style: DiagnosticsTreeStyle.errorProperty,
),
ErrorSpacer(),
- DiagnosticsProperty<dynamic>(
+ DiagnosticsProperty<Object?>(
'The ${child.runtimeType} that did not match the expected child type '
'was created by',
child.debugCreator,
@@ -3012,46 +3000,46 @@
return true;
}
- ChildType _child;
+ ChildType? _child;
/// The render object's unique child.
- ChildType get child => _child;
- set child(ChildType value) {
+ ChildType? get child => _child;
+ set child(ChildType? value) {
if (_child != null)
- dropChild(_child);
+ dropChild(_child!);
_child = value;
if (_child != null)
- adoptChild(_child);
+ adoptChild(_child!);
}
@override
void attach(PipelineOwner owner) {
super.attach(owner);
if (_child != null)
- _child.attach(owner);
+ _child!.attach(owner);
}
@override
void detach() {
super.detach();
if (_child != null)
- _child.detach();
+ _child!.detach();
}
@override
void redepthChildren() {
if (_child != null)
- redepthChild(_child);
+ redepthChild(_child!);
}
@override
void visitChildren(RenderObjectVisitor visitor) {
if (_child != null)
- visitor(_child);
+ visitor(_child!);
}
@override
List<DiagnosticsNode> debugDescribeChildren() {
- return child != null ? <DiagnosticsNode>[child.toDiagnosticsNode(name: 'child')] : <DiagnosticsNode>[];
+ return child != null ? <DiagnosticsNode>[child!.toDiagnosticsNode(name: 'child')] : <DiagnosticsNode>[];
}
}
@@ -3063,9 +3051,9 @@
/// [ContainerRenderObjectMixin.lastChild].
mixin ContainerParentDataMixin<ChildType extends RenderObject> on ParentData {
/// The previous sibling in the parent's child list.
- ChildType previousSibling;
+ ChildType? previousSibling;
/// The next sibling in the parent's child list.
- ChildType nextSibling;
+ ChildType? nextSibling;
/// Clear the sibling pointers.
@override
@@ -3095,20 +3083,20 @@
///
/// Moreover, this is a required mixin for render objects returned to [MultiChildRenderObjectWidget].
mixin ContainerRenderObjectMixin<ChildType extends RenderObject, ParentDataType extends ContainerParentDataMixin<ChildType>> on RenderObject {
- bool _debugUltimatePreviousSiblingOf(ChildType child, { ChildType equals }) {
+ bool _debugUltimatePreviousSiblingOf(ChildType child, { ChildType? equals }) {
ParentDataType childParentData = child.parentData as ParentDataType;
while (childParentData.previousSibling != null) {
assert(childParentData.previousSibling != child);
- child = childParentData.previousSibling;
+ child = childParentData.previousSibling!;
childParentData = child.parentData as ParentDataType;
}
return child == equals;
}
- bool _debugUltimateNextSiblingOf(ChildType child, { ChildType equals }) {
+ bool _debugUltimateNextSiblingOf(ChildType child, { ChildType? equals }) {
ParentDataType childParentData = child.parentData as ParentDataType;
while (childParentData.nextSibling != null) {
assert(childParentData.nextSibling != child);
- child = childParentData.nextSibling;
+ child = childParentData.nextSibling!;
childParentData = child.parentData as ParentDataType;
}
return child == equals;
@@ -3139,13 +3127,13 @@
'a RenderSliver does not understand the RenderBox layout protocol.'
),
ErrorSpacer(),
- DiagnosticsProperty<dynamic>(
+ DiagnosticsProperty<Object?>(
'The $runtimeType that expected a $ChildType child was created by',
debugCreator,
style: DiagnosticsTreeStyle.errorProperty,
),
ErrorSpacer(),
- DiagnosticsProperty<dynamic>(
+ DiagnosticsProperty<Object?>(
'The ${child.runtimeType} that did not match the expected child type '
'was created by',
child.debugCreator,
@@ -3158,9 +3146,9 @@
return true;
}
- ChildType _firstChild;
- ChildType _lastChild;
- void _insertIntoChildList(ChildType child, { ChildType after }) {
+ ChildType? _firstChild;
+ ChildType? _lastChild;
+ void _insertIntoChildList(ChildType child, { ChildType? after }) {
final ParentDataType childParentData = child.parentData as ParentDataType;
assert(childParentData.nextSibling == null);
assert(childParentData.previousSibling == null);
@@ -3170,7 +3158,7 @@
// insert at the start (_firstChild)
childParentData.nextSibling = _firstChild;
if (_firstChild != null) {
- final ParentDataType _firstChildParentData = _firstChild.parentData as ParentDataType;
+ final ParentDataType _firstChildParentData = _firstChild!.parentData as ParentDataType;
_firstChildParentData.previousSibling = child;
}
_firstChild = child;
@@ -3193,8 +3181,8 @@
childParentData.nextSibling = afterParentData.nextSibling;
childParentData.previousSibling = after;
// set up links from siblings to child
- final ParentDataType childPreviousSiblingParentData = childParentData.previousSibling.parentData as ParentDataType;
- final ParentDataType childNextSiblingParentData = childParentData.nextSibling.parentData as ParentDataType;
+ final ParentDataType childPreviousSiblingParentData = childParentData.previousSibling!.parentData as ParentDataType;
+ final ParentDataType childNextSiblingParentData = childParentData.nextSibling!.parentData as ParentDataType;
childPreviousSiblingParentData.nextSibling = child;
childNextSiblingParentData.previousSibling = child;
assert(afterParentData.nextSibling == child);
@@ -3205,7 +3193,7 @@
///
/// If `after` is null, then this inserts the child at the start of the list,
/// and the child becomes the new [firstChild].
- void insert(ChildType child, { ChildType after }) {
+ void insert(ChildType child, { ChildType? after }) {
assert(child != this, 'A RenderObject cannot be inserted into itself.');
assert(after != this, 'A RenderObject cannot simultaneously be both the parent and the sibling of another RenderObject.');
assert(child != after, 'A RenderObject cannot be inserted after itself.');
@@ -3221,7 +3209,7 @@
}
/// Add all the children to the end of this render object's child list.
- void addAll(List<ChildType> children) {
+ void addAll(List<ChildType>? children) {
children?.forEach(add);
}
@@ -3234,14 +3222,14 @@
assert(_firstChild == child);
_firstChild = childParentData.nextSibling;
} else {
- final ParentDataType childPreviousSiblingParentData = childParentData.previousSibling.parentData as ParentDataType;
+ final ParentDataType childPreviousSiblingParentData = childParentData.previousSibling!.parentData as ParentDataType;
childPreviousSiblingParentData.nextSibling = childParentData.nextSibling;
}
if (childParentData.nextSibling == null) {
assert(_lastChild == child);
_lastChild = childParentData.previousSibling;
} else {
- final ParentDataType childNextSiblingParentData = childParentData.nextSibling.parentData as ParentDataType;
+ final ParentDataType childNextSiblingParentData = childParentData.nextSibling!.parentData as ParentDataType;
childNextSiblingParentData.previousSibling = childParentData.previousSibling;
}
childParentData.previousSibling = null;
@@ -3261,10 +3249,10 @@
///
/// More efficient than removing them individually.
void removeAll() {
- ChildType child = _firstChild;
+ ChildType? child = _firstChild;
while (child != null) {
final ParentDataType childParentData = child.parentData as ParentDataType;
- final ChildType next = childParentData.nextSibling;
+ final ChildType? next = childParentData.nextSibling;
childParentData.previousSibling = null;
childParentData.nextSibling = null;
dropChild(child);
@@ -3280,7 +3268,7 @@
/// More efficient than removing and re-adding the child. Requires the child
/// to already be in the child list at some position. Pass null for `after` to
/// move the child to the start of the child list.
- void move(ChildType child, { ChildType after }) {
+ void move(ChildType child, { ChildType? after }) {
assert(child != this);
assert(after != this);
assert(child != after);
@@ -3296,7 +3284,7 @@
@override
void attach(PipelineOwner owner) {
super.attach(owner);
- ChildType child = _firstChild;
+ ChildType? child = _firstChild;
while (child != null) {
child.attach(owner);
final ParentDataType childParentData = child.parentData as ParentDataType;
@@ -3307,7 +3295,7 @@
@override
void detach() {
super.detach();
- ChildType child = _firstChild;
+ ChildType? child = _firstChild;
while (child != null) {
child.detach();
final ParentDataType childParentData = child.parentData as ParentDataType;
@@ -3317,7 +3305,7 @@
@override
void redepthChildren() {
- ChildType child = _firstChild;
+ ChildType? child = _firstChild;
while (child != null) {
redepthChild(child);
final ParentDataType childParentData = child.parentData as ParentDataType;
@@ -3327,7 +3315,7 @@
@override
void visitChildren(RenderObjectVisitor visitor) {
- ChildType child = _firstChild;
+ ChildType? child = _firstChild;
while (child != null) {
visitor(child);
final ParentDataType childParentData = child.parentData as ParentDataType;
@@ -3336,13 +3324,13 @@
}
/// The first child in the child list.
- ChildType get firstChild => _firstChild;
+ ChildType? get firstChild => _firstChild;
/// The last child in the child list.
- ChildType get lastChild => _lastChild;
+ ChildType? get lastChild => _lastChild;
/// The previous child before the given child in the child list.
- ChildType childBefore(ChildType child) {
+ ChildType? childBefore(ChildType child) {
assert(child != null);
assert(child.parent == this);
final ParentDataType childParentData = child.parentData as ParentDataType;
@@ -3350,7 +3338,7 @@
}
/// The next child after the given child in the child list.
- ChildType childAfter(ChildType child) {
+ ChildType? childAfter(ChildType child) {
assert(child != null);
assert(child.parent == this);
final ParentDataType childParentData = child.parentData as ParentDataType;
@@ -3361,7 +3349,7 @@
List<DiagnosticsNode> debugDescribeChildren() {
final List<DiagnosticsNode> children = <DiagnosticsNode>[];
if (firstChild != null) {
- ChildType child = firstChild;
+ ChildType child = firstChild!;
int count = 1;
while (true) {
children.add(child.toDiagnosticsNode(name: 'child $count'));
@@ -3369,7 +3357,7 @@
break;
count += 1;
final ParentDataType childParentData = child.parentData as ParentDataType;
- child = childParentData.nextSibling;
+ child = childParentData.nextSibling!;
}
}
return children;
@@ -3400,12 +3388,12 @@
@override
void attach(covariant PipelineOwner owner) {
super.attach(owner);
- PaintingBinding.instance.systemFonts.addListener(systemFontsDidChange);
+ PaintingBinding.instance!.systemFonts.addListener(systemFontsDidChange);
}
@override
void detach() {
- PaintingBinding.instance.systemFonts.removeListener(systemFontsDidChange);
+ PaintingBinding.instance!.systemFonts.removeListener(systemFontsDidChange);
super.detach();
}
}
@@ -3419,7 +3407,7 @@
/// * [_ContainerSemanticsFragment]: a container class to transport the semantic
/// information of multiple [_InterestingSemanticsFragment] to a parent.
abstract class _SemanticsFragment {
- _SemanticsFragment({@required this.dropsSemanticsOfPreviousSiblings })
+ _SemanticsFragment({ required this.dropsSemanticsOfPreviousSiblings })
: assert (dropsSemanticsOfPreviousSiblings != null);
/// Incorporate the fragments of children into this fragment.
@@ -3457,7 +3445,7 @@
/// obtained via [interestingFragments].
class _ContainerSemanticsFragment extends _SemanticsFragment {
- _ContainerSemanticsFragment({ @required bool dropsSemanticsOfPreviousSiblings })
+ _ContainerSemanticsFragment({ required bool dropsSemanticsOfPreviousSiblings })
: super(dropsSemanticsOfPreviousSiblings: dropsSemanticsOfPreviousSiblings);
@override
@@ -3477,8 +3465,8 @@
/// merged into the parent's [SemanticsNode].
abstract class _InterestingSemanticsFragment extends _SemanticsFragment {
_InterestingSemanticsFragment({
- @required RenderObject owner,
- @required bool dropsSemanticsOfPreviousSiblings,
+ required RenderObject owner,
+ required bool dropsSemanticsOfPreviousSiblings,
}) : assert(owner != null),
_ancestorChain = <RenderObject>[owner],
super(dropsSemanticsOfPreviousSiblings: dropsSemanticsOfPreviousSiblings);
@@ -3500,14 +3488,14 @@
/// * [SemanticsNode.elevationAdjustment] for the source and definition
// of the `elevationAdjustment` argument.
Iterable<SemanticsNode> compileChildren({
- @required Rect parentSemanticsClipRect,
- @required Rect parentPaintClipRect,
- @required double elevationAdjustment,
+ required Rect? parentSemanticsClipRect,
+ required Rect? parentPaintClipRect,
+ required double elevationAdjustment,
});
/// The [SemanticsConfiguration] the child wants to merge into the parent's
/// [SemanticsNode] or null if it doesn't want to merge anything.
- SemanticsConfiguration get config;
+ SemanticsConfiguration? get config;
/// Disallows this fragment to merge any configuration into its parent's
/// [SemanticsNode].
@@ -3536,14 +3524,14 @@
yield this;
}
- Set<SemanticsTag> _tagsForChildren;
+ Set<SemanticsTag>? _tagsForChildren;
/// Tag all children produced by [compileChildren] with `tags`.
- void addTags(Iterable<SemanticsTag> tags) {
+ void addTags(Iterable<SemanticsTag>? tags) {
if (tags == null || tags.isEmpty)
return;
_tagsForChildren ??= <SemanticsTag>{};
- _tagsForChildren.addAll(tags);
+ _tagsForChildren!.addAll(tags);
}
/// Adds the geometric information of `ancestor` to this object.
@@ -3566,13 +3554,13 @@
/// [children].
class _RootSemanticsFragment extends _InterestingSemanticsFragment {
_RootSemanticsFragment({
- @required RenderObject owner,
- @required bool dropsSemanticsOfPreviousSiblings,
+ required RenderObject owner,
+ required bool dropsSemanticsOfPreviousSiblings,
}) : super(owner: owner, dropsSemanticsOfPreviousSiblings: dropsSemanticsOfPreviousSiblings);
@override
- Iterable<SemanticsNode> compileChildren({ Rect parentSemanticsClipRect, Rect parentPaintClipRect, double elevationAdjustment }) sync* {
- assert(_tagsForChildren == null || _tagsForChildren.isEmpty);
+ Iterable<SemanticsNode> compileChildren({ Rect? parentSemanticsClipRect, Rect? parentPaintClipRect, required double elevationAdjustment }) sync* {
+ assert(_tagsForChildren == null || _tagsForChildren!.isEmpty);
assert(parentSemanticsClipRect == null);
assert(parentPaintClipRect == null);
assert(_ancestorChain.length == 1);
@@ -3580,9 +3568,9 @@
owner._semantics ??= SemanticsNode.root(
showOnScreen: owner.showOnScreen,
- owner: owner.owner.semanticsOwner,
+ owner: owner.owner!.semanticsOwner!,
);
- final SemanticsNode node = owner._semantics;
+ final SemanticsNode node = owner._semantics!;
assert(MatrixUtils.matrixEquals(node.transform, Matrix4.identity()));
assert(node.parentSemanticsClipRect == null);
assert(node.parentPaintClipRect == null);
@@ -3611,7 +3599,7 @@
}
@override
- SemanticsConfiguration get config => null;
+ SemanticsConfiguration? get config => null;
final List<_InterestingSemanticsFragment> _children = <_InterestingSemanticsFragment>[];
@@ -3646,10 +3634,10 @@
/// [SemanticsNode].
class _SwitchableSemanticsFragment extends _InterestingSemanticsFragment {
_SwitchableSemanticsFragment({
- @required bool mergeIntoParent,
- @required SemanticsConfiguration config,
- @required RenderObject owner,
- @required bool dropsSemanticsOfPreviousSiblings,
+ required bool mergeIntoParent,
+ required SemanticsConfiguration config,
+ required RenderObject owner,
+ required bool dropsSemanticsOfPreviousSiblings,
}) : _mergeIntoParent = mergeIntoParent,
_config = config,
assert(mergeIntoParent != null),
@@ -3662,7 +3650,7 @@
final List<_InterestingSemanticsFragment> _children = <_InterestingSemanticsFragment>[];
@override
- Iterable<SemanticsNode> compileChildren({ Rect parentSemanticsClipRect, Rect parentPaintClipRect, double elevationAdjustment }) sync* {
+ Iterable<SemanticsNode> compileChildren({ Rect? parentSemanticsClipRect, Rect? parentPaintClipRect, required double elevationAdjustment }) sync* {
if (!_isExplicit) {
owner._semantics = null;
for (final _InterestingSemanticsFragment fragment in _children) {
@@ -3680,7 +3668,7 @@
return;
}
- final _SemanticsGeometry geometry = _needsGeometryUpdate
+ final _SemanticsGeometry? geometry = _needsGeometryUpdate
? _SemanticsGeometry(parentSemanticsClipRect: parentSemanticsClipRect, parentPaintClipRect: parentPaintClipRect, ancestors: _ancestorChain)
: null;
@@ -3688,7 +3676,7 @@
return; // Drop the node, it's not going to be visible.
owner._semantics ??= SemanticsNode(showOnScreen: owner.showOnScreen);
- final SemanticsNode node = owner._semantics
+ final SemanticsNode node = owner._semantics!
..isMergedIntoParent = _mergeIntoParent
..tags = _tagsForChildren;
@@ -3729,7 +3717,7 @@
}
@override
- SemanticsConfiguration get config {
+ SemanticsConfiguration? get config {
return _isExplicit ? null : _config;
}
@@ -3740,7 +3728,7 @@
if (fragment.config == null)
continue;
_ensureConfigIsWritable();
- _config.absorb(fragment.config);
+ _config.absorb(fragment.config!);
}
}
@@ -3770,13 +3758,13 @@
/// information to compute. As a result, this fragment also doesn't carry any
/// semantics information either.
class _AbortingSemanticsFragment extends _InterestingSemanticsFragment {
- _AbortingSemanticsFragment({@required RenderObject owner}) : super(owner: owner, dropsSemanticsOfPreviousSiblings: false);
+ _AbortingSemanticsFragment({required RenderObject owner}) : super(owner: owner, dropsSemanticsOfPreviousSiblings: false);
@override
bool get abortsWalk => true;
@override
- SemanticsConfiguration get config => null;
+ SemanticsConfiguration? get config => null;
@override
void addAll(Iterable<_InterestingSemanticsFragment> fragments) {
@@ -3784,8 +3772,8 @@
}
@override
- Iterable<SemanticsNode> compileChildren({ Rect parentSemanticsClipRect, Rect parentPaintClipRect, double elevationAdjustment }) sync* {
- yield owner._semantics;
+ Iterable<SemanticsNode> compileChildren({ Rect? parentSemanticsClipRect, Rect? parentPaintClipRect, required double elevationAdjustment }) sync* {
+ yield owner._semantics!;
}
@override
@@ -3807,26 +3795,26 @@
/// (first [RenderObject] in the list) and its closest ancestor [RenderObject]
/// that also owns its own [SemanticsNode] (last [RenderObject] in the list).
_SemanticsGeometry({
- @required Rect parentSemanticsClipRect,
- @required Rect parentPaintClipRect,
- @required List<RenderObject> ancestors,
+ required Rect? parentSemanticsClipRect,
+ required Rect? parentPaintClipRect,
+ required List<RenderObject> ancestors,
}) {
_computeValues(parentSemanticsClipRect, parentPaintClipRect, ancestors);
}
- Rect _paintClipRect;
- Rect _semanticsClipRect;
- Matrix4 _transform;
- Rect _rect;
+ Rect? _paintClipRect;
+ Rect? _semanticsClipRect;
+ late Matrix4 _transform;
+ late Rect _rect;
/// Value for [SemanticsNode.transform].
Matrix4 get transform => _transform;
/// Value for [SemanticsNode.parentSemanticsClipRect].
- Rect get semanticsClipRect => _semanticsClipRect;
+ Rect? get semanticsClipRect => _semanticsClipRect;
/// Value for [SemanticsNode.parentPaintClipRect].
- Rect get paintClipRect => _paintClipRect;
+ Rect? get paintClipRect => _paintClipRect;
/// Value for [SemanticsNode.rect].
Rect get rect => _rect;
@@ -3837,7 +3825,7 @@
///
/// * [RenderObject.describeSemanticsClip], typically used to determine `parentSemanticsClipRect`.
/// * [RenderObject.describeApproximatePaintClip], typically used to determine `parentPaintClipRect`.
- void _computeValues(Rect parentSemanticsClipRect, Rect parentPaintClipRect, List<RenderObject> ancestors) {
+ void _computeValues(Rect? parentSemanticsClipRect, Rect? parentPaintClipRect, List<RenderObject> ancestors) {
assert(ancestors.length > 1);
_transform = Matrix4.identity();
@@ -3846,7 +3834,7 @@
for (int index = ancestors.length-1; index > 0; index -= 1) {
final RenderObject parent = ancestors[index];
final RenderObject child = ancestors[index-1];
- final Rect parentSemanticsClipRect = parent.describeSemanticsClip(child);
+ final Rect? parentSemanticsClipRect = parent.describeSemanticsClip(child);
if (parentSemanticsClipRect != null) {
_semanticsClipRect = parentSemanticsClipRect;
_paintClipRect = _intersectRects(_paintClipRect, parent.describeApproximatePaintClip(child));
@@ -3860,9 +3848,9 @@
}
final RenderObject owner = ancestors.first;
- _rect = _semanticsClipRect == null ? owner.semanticBounds : _semanticsClipRect.intersect(owner.semanticBounds);
+ _rect = _semanticsClipRect == null ? owner.semanticBounds : _semanticsClipRect!.intersect(owner.semanticBounds);
if (_paintClipRect != null) {
- final Rect paintRect = _paintClipRect.intersect(_rect);
+ final Rect paintRect = _paintClipRect!.intersect(_rect);
_markAsHidden = paintRect.isEmpty && !_rect.isEmpty;
if (!_markAsHidden)
_rect = paintRect;
@@ -3879,7 +3867,7 @@
static final Matrix4 _temporaryTransformHolder = Matrix4.zero();
/// From parent to child coordinate system.
- static Rect _transformRect(Rect rect, Matrix4 transform) {
+ static Rect? _transformRect(Rect? rect, Matrix4 transform) {
assert(transform != null);
if (rect == null)
return null;
@@ -3916,7 +3904,7 @@
ancestor.applyPaintTransform(child, clipRectTransform);
}
- static Rect _intersectRects(Rect a, Rect b) {
+ static Rect? _intersectRects(Rect? a, Rect? b) {
if (a == null)
return b;
if (b == null)
diff --git a/packages/flutter/lib/src/rendering/paragraph.dart b/packages/flutter/lib/src/rendering/paragraph.dart
index a36c365..e5d2507 100644
--- a/packages/flutter/lib/src/rendering/paragraph.dart
+++ b/packages/flutter/lib/src/rendering/paragraph.dart
@@ -2,8 +2,6 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-// @dart = 2.8
-
import 'dart:collection';
import 'dart:math' as math;
import 'dart:ui' as ui show Gradient, Shader, TextBox, PlaceholderAlignment, TextHeightBehavior;
@@ -43,7 +41,7 @@
/// Parent data for use with [RenderParagraph].
class TextParentData extends ContainerBoxParentData<RenderBox> {
/// The scaling of the text.
- double scale;
+ double? scale;
@override
String toString() {
@@ -70,16 +68,16 @@
/// it is not null, it must be greater than zero.
RenderParagraph(InlineSpan text, {
TextAlign textAlign = TextAlign.start,
- @required TextDirection textDirection,
+ required TextDirection textDirection,
bool softWrap = true,
TextOverflow overflow = TextOverflow.clip,
double textScaleFactor = 1.0,
- int maxLines,
- Locale locale,
- StrutStyle strutStyle,
+ int? maxLines,
+ Locale? locale,
+ StrutStyle? strutStyle,
TextWidthBasis textWidthBasis = TextWidthBasis.parent,
- ui.TextHeightBehavior textHeightBehavior,
- List<RenderBox> children,
+ ui.TextHeightBehavior? textHeightBehavior,
+ List<RenderBox>? children,
}) : assert(text != null),
assert(text.debugAssertIsValid()),
assert(textAlign != null),
@@ -116,10 +114,10 @@
final TextPainter _textPainter;
/// The text to display.
- InlineSpan get text => _textPainter.text;
+ InlineSpan get text => _textPainter.text!;
set text(InlineSpan value) {
assert(value != null);
- switch (_textPainter.text.compareTo(value)) {
+ switch (_textPainter.text!.compareTo(value)) {
case RenderComparison.identical:
case RenderComparison.metadata:
return;
@@ -138,13 +136,12 @@
}
}
- List<PlaceholderSpan> _placeholderSpans;
+ late List<PlaceholderSpan> _placeholderSpans;
void _extractPlaceholderSpans(InlineSpan span) {
_placeholderSpans = <PlaceholderSpan>[];
span.visitChildren((InlineSpan span) {
if (span is PlaceholderSpan) {
- final PlaceholderSpan placeholderSpan = span;
- _placeholderSpans.add(placeholderSpan);
+ _placeholderSpans.add(span);
}
return true;
});
@@ -173,7 +170,7 @@
/// its left.
///
/// This must not be null.
- TextDirection get textDirection => _textPainter.textDirection;
+ TextDirection get textDirection => _textPainter.textDirection!;
set textDirection(TextDirection value) {
assert(value != null);
if (_textPainter.textDirection == value)
@@ -228,10 +225,10 @@
/// An optional maximum number of lines for the text to span, wrapping if
/// necessary. If the text exceeds the given number of lines, it will be
/// truncated according to [overflow] and [softWrap].
- int get maxLines => _textPainter.maxLines;
+ int? get maxLines => _textPainter.maxLines;
/// The value may be null. If it is not null, then it must be greater than
/// zero.
- set maxLines(int value) {
+ set maxLines(int? value) {
assert(value == null || value > 0);
if (_textPainter.maxLines == value)
return;
@@ -248,9 +245,9 @@
/// on the locale. For example the '骨' character is rendered differently in
/// the Chinese and Japanese locales. In these cases the [locale] may be used
/// to select a locale-specific font.
- Locale get locale => _textPainter.locale;
+ Locale? get locale => _textPainter.locale;
/// The value may be null.
- set locale(Locale value) {
+ set locale(Locale? value) {
if (_textPainter.locale == value)
return;
_textPainter.locale = value;
@@ -259,9 +256,9 @@
}
/// {@macro flutter.painting.textPainter.strutStyle}
- StrutStyle get strutStyle => _textPainter.strutStyle;
+ StrutStyle? get strutStyle => _textPainter.strutStyle;
/// The value may be null.
- set strutStyle(StrutStyle value) {
+ set strutStyle(StrutStyle? value) {
if (_textPainter.strutStyle == value)
return;
_textPainter.strutStyle = value;
@@ -281,8 +278,8 @@
}
/// {@macro flutter.dart:ui.textHeightBehavior}
- ui.TextHeightBehavior get textHeightBehavior => _textPainter.textHeightBehavior;
- set textHeightBehavior(ui.TextHeightBehavior value) {
+ ui.TextHeightBehavior? get textHeightBehavior => _textPainter.textHeightBehavior;
+ set textHeightBehavior(ui.TextHeightBehavior? value) {
if (_textPainter.textHeightBehavior == value)
return;
_textPainter.textHeightBehavior = value;
@@ -369,8 +366,8 @@
}
void _computeChildrenWidthWithMaxIntrinsics(double height) {
- RenderBox child = firstChild;
- final List<PlaceholderDimensions> placeholderDimensions = List<PlaceholderDimensions>(childCount);
+ RenderBox? child = firstChild;
+ final List<PlaceholderDimensions> placeholderDimensions = List<PlaceholderDimensions>.filled(childCount, PlaceholderDimensions.empty, growable: false);
int childIndex = 0;
// Takes textScaleFactor into account because the content of the placeholder
// span will be scale up when it paints.
@@ -386,12 +383,12 @@
child = childAfter(child);
childIndex += 1;
}
- _textPainter.setPlaceholderDimensions(placeholderDimensions);
+ _textPainter.setPlaceholderDimensions(placeholderDimensions.cast<PlaceholderDimensions>());
}
void _computeChildrenWidthWithMinIntrinsics(double height) {
- RenderBox child = firstChild;
- final List<PlaceholderDimensions> placeholderDimensions = List<PlaceholderDimensions>(childCount);
+ RenderBox? child = firstChild;
+ final List<PlaceholderDimensions> placeholderDimensions = List<PlaceholderDimensions>.filled(childCount, PlaceholderDimensions.empty, growable: false);
int childIndex = 0;
// Takes textScaleFactor into account because the content of the placeholder
// span will be scale up when it paints.
@@ -407,12 +404,12 @@
child = childAfter(child);
childIndex += 1;
}
- _textPainter.setPlaceholderDimensions(placeholderDimensions);
+ _textPainter.setPlaceholderDimensions(placeholderDimensions.cast<PlaceholderDimensions>());
}
void _computeChildrenHeightWithMinIntrinsics(double width) {
- RenderBox child = firstChild;
- final List<PlaceholderDimensions> placeholderDimensions = List<PlaceholderDimensions>(childCount);
+ RenderBox? child = firstChild;
+ final List<PlaceholderDimensions> placeholderDimensions = List<PlaceholderDimensions>.filled(childCount, PlaceholderDimensions.empty, growable: false);
int childIndex = 0;
// Takes textScaleFactor into account because the content of the placeholder
// span will be scale up when it paints.
@@ -428,15 +425,15 @@
child = childAfter(child);
childIndex += 1;
}
- _textPainter.setPlaceholderDimensions(placeholderDimensions);
+ _textPainter.setPlaceholderDimensions(placeholderDimensions.cast<PlaceholderDimensions>());
}
@override
bool hitTestSelf(Offset position) => true;
@override
- bool hitTestChildren(BoxHitTestResult result, { Offset position }) {
- RenderBox child = firstChild;
+ bool hitTestChildren(BoxHitTestResult result, { required Offset position }) {
+ RenderBox? child = firstChild;
while (child != null) {
final TextParentData textParentData = child.parentData as TextParentData;
final Matrix4 transform = Matrix4.translationValues(
@@ -451,13 +448,13 @@
final bool isHit = result.addWithPaintTransform(
transform: transform,
position: position,
- hitTest: (BoxHitTestResult result, Offset transformed) {
+ hitTest: (BoxHitTestResult result, Offset? transformed) {
assert(() {
- final Offset manualPosition = (position - textParentData.offset) / textParentData.scale;
- return (transformed.dx - manualPosition.dx).abs() < precisionErrorTolerance
+ final Offset manualPosition = (position - textParentData.offset) / textParentData.scale!;
+ return (transformed!.dx - manualPosition.dx).abs() < precisionErrorTolerance
&& (transformed.dy - manualPosition.dy).abs() < precisionErrorTolerance;
}());
- return child.hitTest(result, position: transformed);
+ return child!.hitTest(result, position: transformed!);
},
);
if (isHit) {
@@ -476,18 +473,17 @@
_layoutTextWithConstraints(constraints);
final Offset offset = entry.localPosition;
final TextPosition position = _textPainter.getPositionForOffset(offset);
- final InlineSpan span = _textPainter.text.getSpanForPosition(position);
+ final InlineSpan? span = _textPainter.text!.getSpanForPosition(position);
if (span == null) {
return;
}
if (span is TextSpan) {
- final TextSpan textSpan = span;
- textSpan.recognizer?.addPointer(event as PointerDownEvent);
+ span.recognizer?.addPointer(event);
}
}
bool _needsClipping = false;
- ui.Shader _overflowShader;
+ ui.Shader? _overflowShader;
/// Whether this paragraph currently has a [dart:ui.Shader] for its overflow
/// effect.
@@ -517,7 +513,7 @@
// These need to be cached because the text painter's placeholder dimensions
// will be overwritten during intrinsic width/height calculations and must be
// restored to the original values before final layout and painting.
- List<PlaceholderDimensions> _placeholderDimensions;
+ List<PlaceholderDimensions>? _placeholderDimensions;
void _layoutTextWithConstraints(BoxConstraints constraints) {
_textPainter.setPlaceholderDimensions(_placeholderDimensions);
@@ -532,8 +528,8 @@
if (childCount == 0) {
return;
}
- RenderBox child = firstChild;
- _placeholderDimensions = List<PlaceholderDimensions>(childCount);
+ RenderBox? child = firstChild;
+ final List<PlaceholderDimensions> placeholderDimensions = List<PlaceholderDimensions>.filled(childCount, PlaceholderDimensions.empty, growable: false);
int childIndex = 0;
BoxConstraints boxConstraints = BoxConstraints(maxWidth: constraints.maxWidth);
// The content will be enlarged by textScaleFactor during painting phase.
@@ -547,11 +543,11 @@
boxConstraints,
parentUsesSize: true,
);
- double baselineOffset;
+ double? baselineOffset;
switch (_placeholderSpans[childIndex].alignment) {
case ui.PlaceholderAlignment.baseline: {
baselineOffset = child.getDistanceToBaseline(
- _placeholderSpans[childIndex].baseline
+ _placeholderSpans[childIndex].baseline!
);
break;
}
@@ -560,7 +556,7 @@
break;
}
}
- _placeholderDimensions[childIndex] = PlaceholderDimensions(
+ placeholderDimensions[childIndex] = PlaceholderDimensions(
size: child.size,
alignment: _placeholderSpans[childIndex].alignment,
baseline: _placeholderSpans[childIndex].baseline,
@@ -569,20 +565,21 @@
child = childAfter(child);
childIndex += 1;
}
+ _placeholderDimensions = placeholderDimensions.cast<PlaceholderDimensions>();
}
// Iterate through the laid-out children and set the parentData offsets based
// off of the placeholders inserted for each child.
void _setParentData() {
- RenderBox child = firstChild;
+ RenderBox? child = firstChild;
int childIndex = 0;
- while (child != null && childIndex < _textPainter.inlinePlaceholderBoxes.length) {
+ while (child != null && childIndex < _textPainter.inlinePlaceholderBoxes!.length) {
final TextParentData textParentData = child.parentData as TextParentData;
textParentData.offset = Offset(
- _textPainter.inlinePlaceholderBoxes[childIndex].left,
- _textPainter.inlinePlaceholderBoxes[childIndex].top,
+ _textPainter.inlinePlaceholderBoxes![childIndex].left,
+ _textPainter.inlinePlaceholderBoxes![childIndex].top,
);
- textParentData.scale = _textPainter.inlinePlaceholderScales[childIndex];
+ textParentData.scale = _textPainter.inlinePlaceholderScales![childIndex];
child = childAfter(child);
childIndex += 1;
}
@@ -627,7 +624,7 @@
assert(textDirection != null);
_needsClipping = true;
final TextPainter fadeSizePainter = TextPainter(
- text: TextSpan(style: _textPainter.text.style, text: '\u2026'),
+ text: TextSpan(style: _textPainter.text!.style, text: '\u2026'),
textDirection: textDirection,
textScaleFactor: textScaleFactor,
locale: locale,
@@ -702,23 +699,23 @@
}
_textPainter.paint(context.canvas, offset);
- RenderBox child = firstChild;
+ RenderBox? child = firstChild;
int childIndex = 0;
// childIndex might be out of index of placeholder boxes. This can happen
// if engine truncates children due to ellipsis. Sadly, we would not know
// it until we finish layout, and RenderObject is in immutable state at
// this point.
- while (child != null && childIndex < _textPainter.inlinePlaceholderBoxes.length) {
+ while (child != null && childIndex < _textPainter.inlinePlaceholderBoxes!.length) {
final TextParentData textParentData = child.parentData as TextParentData;
- final double scale = textParentData.scale;
+ final double scale = textParentData.scale!;
context.pushTransform(
needsCompositing,
offset + textParentData.offset,
Matrix4.diagonal3Values(scale, scale, scale),
(PaintingContext context, Offset offset) {
context.paintChild(
- child,
+ child!,
offset,
);
},
@@ -800,7 +797,7 @@
/// Collected during [describeSemanticsConfiguration], used by
/// [assembleSemanticsNode] and [_combineSemanticsInfo].
- List<InlineSpanSemanticsInformation> _semanticsInfo;
+ List<InlineSpanSemanticsInformation>? _semanticsInfo;
/// Combines _semanticsInfo entries where permissible, determined by
/// [InlineSpanSemanticsInformation.requiresOwnNode].
@@ -808,8 +805,10 @@
assert(_semanticsInfo != null);
final List<InlineSpanSemanticsInformation> combined = <InlineSpanSemanticsInformation>[];
String workingText = '';
- String workingLabel;
- for (final InlineSpanSemanticsInformation info in _semanticsInfo) {
+ // TODO(ianh): this algorithm is internally inconsistent. workingText
+ // never becomes null, but we check for it being so below.
+ String? workingLabel;
+ for (final InlineSpanSemanticsInformation info in _semanticsInfo!) {
if (info.requiresOwnNode) {
if (workingText != null) {
combined.add(InlineSpanSemanticsInformation(
@@ -824,7 +823,7 @@
workingText += info.text;
workingLabel ??= '';
if (info.semanticsLabel != null) {
- workingLabel += info.semanticsLabel;
+ workingLabel += info.semanticsLabel!;
} else {
workingLabel += info.text;
}
@@ -835,7 +834,7 @@
workingText,
semanticsLabel: workingLabel,
));
- } else {
+ } else { // ignore: dead_code
assert(workingLabel != null);
}
return combined;
@@ -846,12 +845,12 @@
super.describeSemanticsConfiguration(config);
_semanticsInfo = text.getSemanticsInformation();
- if (_semanticsInfo.any((InlineSpanSemanticsInformation info) => info.recognizer != null)) {
+ if (_semanticsInfo!.any((InlineSpanSemanticsInformation info) => info.recognizer != null)) {
config.explicitChildNodes = true;
config.isSemanticBoundary = true;
} else {
final StringBuffer buffer = StringBuffer();
- for (final InlineSpanSemanticsInformation info in _semanticsInfo) {
+ for (final InlineSpanSemanticsInformation info in _semanticsInfo!) {
buffer.write(info.semanticsLabel ?? info.text);
}
config.label = buffer.toString();
@@ -863,18 +862,18 @@
// can be re-used when [assembleSemanticsNode] is called again. This ensures
// stable ids for the [SemanticsNode]s of [TextSpan]s across
// [assembleSemanticsNode] invocations.
- Queue<SemanticsNode> _cachedChildNodes;
+ Queue<SemanticsNode>? _cachedChildNodes;
@override
void assembleSemanticsNode(SemanticsNode node, SemanticsConfiguration config, Iterable<SemanticsNode> children) {
- assert(_semanticsInfo != null && _semanticsInfo.isNotEmpty);
+ assert(_semanticsInfo != null && _semanticsInfo!.isNotEmpty);
final List<SemanticsNode> newChildren = <SemanticsNode>[];
TextDirection currentDirection = textDirection;
Rect currentRect;
double ordinal = 0.0;
int start = 0;
int placeholderIndex = 0;
- RenderBox child = firstChild;
+ RenderBox? child = firstChild;
final Queue<SemanticsNode> newChildCache = Queue<SemanticsNode>();
for (final InlineSpanSemanticsInformation info in _combineSemanticsInfo()) {
final TextDirection initialDirection = currentDirection;
@@ -911,12 +910,12 @@
if (info.isPlaceholder) {
final SemanticsNode childNode = children.elementAt(placeholderIndex++);
- final TextParentData parentData = child.parentData as TextParentData;
+ final TextParentData parentData = child!.parentData as TextParentData;
childNode.rect = Rect.fromLTWH(
childNode.rect.left,
childNode.rect.top,
- childNode.rect.width * parentData.scale,
- childNode.rect.height * parentData.scale,
+ childNode.rect.width * parentData.scale!,
+ childNode.rect.height * parentData.scale!,
);
newChildren.add(childNode);
child = childAfter(child);
@@ -925,7 +924,7 @@
..sortKey = OrdinalSortKey(ordinal++)
..textDirection = initialDirection
..label = info.semanticsLabel ?? info.text;
- final GestureRecognizer recognizer = info.recognizer;
+ final GestureRecognizer? recognizer = info.recognizer;
if (recognizer != null) {
if (recognizer is TapGestureRecognizer) {
configuration.onTap = recognizer.onTap;
@@ -940,7 +939,7 @@
}
}
final SemanticsNode newChild = (_cachedChildNodes?.isNotEmpty == true)
- ? _cachedChildNodes.removeFirst()
+ ? _cachedChildNodes!.removeFirst()
: SemanticsNode();
newChild
..updateWith(config: configuration)
diff --git a/packages/flutter/lib/src/rendering/performance_overlay.dart b/packages/flutter/lib/src/rendering/performance_overlay.dart
index 56d061e..9ec2952 100644
--- a/packages/flutter/lib/src/rendering/performance_overlay.dart
+++ b/packages/flutter/lib/src/rendering/performance_overlay.dart
@@ -2,8 +2,6 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-// @dart = 2.8
-
import 'box.dart';
import 'layer.dart';
import 'object.dart';
diff --git a/packages/flutter/lib/src/rendering/platform_view.dart b/packages/flutter/lib/src/rendering/platform_view.dart
index f6bb801..3b8906f 100644
--- a/packages/flutter/lib/src/rendering/platform_view.dart
+++ b/packages/flutter/lib/src/rendering/platform_view.dart
@@ -2,8 +2,6 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-// @dart = 2.8
-
import 'dart:async';
import 'dart:ui';
@@ -41,7 +39,7 @@
ready,
}
-bool _factoryTypesSetEquals<T>(Set<Factory<T>> a, Set<Factory<T>> b) {
+bool _factoryTypesSetEquals<T>(Set<Factory<T>>? a, Set<Factory<T>>? b) {
if (a == b) {
return true;
}
@@ -83,9 +81,9 @@
/// Creates a render object for an Android view.
RenderAndroidView({
- @required AndroidViewController viewController,
- @required PlatformViewHitTestBehavior hitTestBehavior,
- @required Set<Factory<OneSequenceGestureRecognizer>> gestureRecognizers,
+ required AndroidViewController viewController,
+ required PlatformViewHitTestBehavior hitTestBehavior,
+ required Set<Factory<OneSequenceGestureRecognizer>> gestureRecognizers,
}) : assert(viewController != null),
assert(hitTestBehavior != null),
assert(gestureRecognizers != null),
@@ -157,7 +155,7 @@
_sizePlatformView();
}
- Size _currentAndroidViewSize;
+ late Size _currentAndroidViewSize;
Future<void> _sizePlatformView() async {
// Android virtual displays cannot have a zero size.
@@ -211,7 +209,7 @@
// _currentAndroidViewSize.
context.addLayer(TextureLayer(
rect: offset & _currentAndroidViewSize,
- textureId: _viewController.textureId,
+ textureId: _viewController.textureId!,
freeze: _state == _PlatformViewState.resizing,
));
}
@@ -255,9 +253,9 @@
///
/// The `viewId`, `hitTestBehavior`, and `gestureRecognizers` parameters must not be null.
RenderUiKitView({
- @required UiKitViewController viewController,
- @required this.hitTestBehavior,
- @required Set<Factory<OneSequenceGestureRecognizer>> gestureRecognizers,
+ required UiKitViewController viewController,
+ required this.hitTestBehavior,
+ required Set<Factory<OneSequenceGestureRecognizer>> gestureRecognizers,
}) : assert(viewController != null),
assert(hitTestBehavior != null),
assert(gestureRecognizers != null),
@@ -310,9 +308,9 @@
@override
bool get isRepaintBoundary => true;
- _UiKitViewGestureRecognizer _gestureRecognizer;
+ _UiKitViewGestureRecognizer? _gestureRecognizer;
- PointerEvent _lastPointerDownEvent;
+ PointerEvent? _lastPointerDownEvent;
@override
void performResize() {
@@ -328,8 +326,8 @@
}
@override
- bool hitTest(BoxHitTestResult result, { Offset position }) {
- if (hitTestBehavior == PlatformViewHitTestBehavior.transparent || !size.contains(position))
+ bool hitTest(BoxHitTestResult result, { Offset? position }) {
+ if (hitTestBehavior == PlatformViewHitTestBehavior.transparent || !size.contains(position!))
return false;
result.add(BoxHitTestEntry(this, position));
return hitTestBehavior == PlatformViewHitTestBehavior.opaque;
@@ -343,7 +341,7 @@
if (event is! PointerDownEvent) {
return;
}
- _gestureRecognizer.addPointer(event as PointerDownEvent);
+ _gestureRecognizer!.addPointer(event);
_lastPointerDownEvent = event.original ?? event;
}
@@ -375,13 +373,13 @@
@override
void attach(PipelineOwner owner) {
super.attach(owner);
- GestureBinding.instance.pointerRouter.addGlobalRoute(_handleGlobalPointerEvent);
+ GestureBinding.instance!.pointerRouter.addGlobalRoute(_handleGlobalPointerEvent);
}
@override
void detach() {
- GestureBinding.instance.pointerRouter.removeGlobalRoute(_handleGlobalPointerEvent);
- _gestureRecognizer.reset();
+ GestureBinding.instance!.pointerRouter.removeGlobalRoute(_handleGlobalPointerEvent);
+ _gestureRecognizer!.reset();
super.detach();
}
}
@@ -395,10 +393,10 @@
_UiKitViewGestureRecognizer(
this.controller,
this.gestureRecognizerFactories, {
- PointerDeviceKind kind,
+ PointerDeviceKind? kind,
}) : super(kind: kind) {
- team = GestureArenaTeam();
- team.captain = this;
+ team = GestureArenaTeam()
+ ..captain = this;
_gestureRecognizers = gestureRecognizerFactories.map(
(Factory<OneSequenceGestureRecognizer> recognizerFactory) {
final OneSequenceGestureRecognizer gestureRecognizer = recognizerFactory.constructor();
@@ -423,7 +421,7 @@
// TODO(amirh): get a list of GestureRecognizers here.
// https://github.com/flutter/flutter/issues/20953
final Set<Factory<OneSequenceGestureRecognizer>> gestureRecognizerFactories;
- Set<OneSequenceGestureRecognizer> _gestureRecognizers;
+ late Set<OneSequenceGestureRecognizer> _gestureRecognizers;
final UiKitViewController controller;
@@ -473,10 +471,10 @@
_PlatformViewGestureRecognizer(
_HandlePointerEvent handlePointerEvent,
this.gestureRecognizerFactories, {
- PointerDeviceKind kind,
+ PointerDeviceKind? kind,
}) : super(kind: kind) {
- team = GestureArenaTeam();
- team.captain = this;
+ team = GestureArenaTeam()
+ ..captain = this;
_gestureRecognizers = gestureRecognizerFactories.map(
(Factory<OneSequenceGestureRecognizer> recognizerFactory) {
final OneSequenceGestureRecognizer gestureRecognizer = recognizerFactory.constructor();
@@ -497,7 +495,7 @@
_handlePointerEvent = handlePointerEvent;
}
- _HandlePointerEvent _handlePointerEvent;
+ late _HandlePointerEvent _handlePointerEvent;
// Maps a pointer to a list of its cached pointer events.
// Before the arena for a pointer is resolved all events are cached here, if we win the arena
@@ -513,7 +511,7 @@
// TODO(amirh): get a list of GestureRecognizers here.
// https://github.com/flutter/flutter/issues/20953
final Set<Factory<OneSequenceGestureRecognizer>> gestureRecognizerFactories;
- Set<OneSequenceGestureRecognizer> _gestureRecognizers;
+ late Set<OneSequenceGestureRecognizer> _gestureRecognizers;
@override
void addAllowedPointer(PointerDownEvent event) {
@@ -555,7 +553,7 @@
if (!cachedEvents.containsKey(event.pointer)) {
cachedEvents[event.pointer] = <PointerEvent> [];
}
- cachedEvents[event.pointer].add(event);
+ cachedEvents[event.pointer]!.add(event);
}
void _flushPointerCache(int pointer) {
@@ -587,9 +585,9 @@
///
/// The `controller` parameter must not be null.
PlatformViewRenderBox({
- @required PlatformViewController controller,
- @required PlatformViewHitTestBehavior hitTestBehavior,
- @required Set<Factory<OneSequenceGestureRecognizer>> gestureRecognizers,
+ required PlatformViewController controller,
+ required PlatformViewHitTestBehavior hitTestBehavior,
+ required Set<Factory<OneSequenceGestureRecognizer>> gestureRecognizers,
}) : assert(controller != null && controller.viewId != null && controller.viewId > -1),
assert(hitTestBehavior != null),
assert(gestureRecognizers != null),
@@ -670,9 +668,9 @@
markNeedsPaint();
}
}
- PlatformViewHitTestBehavior _hitTestBehavior;
+ PlatformViewHitTestBehavior? _hitTestBehavior;
- _HandlePointerEvent _handlePointerEvent;
+ _HandlePointerEvent? _handlePointerEvent;
/// {@macro flutter.rendering.platformView.updateGestureRecognizers}
///
@@ -692,10 +690,10 @@
_handlePointerEvent = handlePointerEvent;
}
- _PlatformViewGestureRecognizer _gestureRecognizer;
+ _PlatformViewGestureRecognizer? _gestureRecognizer;
@override
- bool hitTest(BoxHitTestResult result, { Offset position }) {
+ bool hitTest(BoxHitTestResult result, { required Offset position }) {
if (_hitTestBehavior == PlatformViewHitTestBehavior.transparent || !size.contains(position)) {
return false;
}
@@ -707,17 +705,17 @@
bool hitTestSelf(Offset position) => _hitTestBehavior != PlatformViewHitTestBehavior.transparent;
@override
- PointerEnterEventListener get onEnter => null;
+ PointerEnterEventListener? get onEnter => null;
@override
PointerHoverEventListener get onHover => _handleHover;
void _handleHover(PointerHoverEvent event) {
if (_handlePointerEvent != null)
- _handlePointerEvent(event);
+ _handlePointerEvent!(event);
}
@override
- PointerExitEventListener get onExit => null;
+ PointerExitEventListener? get onExit => null;
@override
MouseCursor get cursor => MouseCursor.uncontrolled;
@@ -725,13 +723,13 @@
@override
void handleEvent(PointerEvent event, HitTestEntry entry) {
if (event is PointerDownEvent) {
- _gestureRecognizer.addPointer(event);
+ _gestureRecognizer!.addPointer(event);
}
}
@override
void detach() {
- _gestureRecognizer.reset();
+ _gestureRecognizer!.reset();
super.detach();
}
}
diff --git a/packages/flutter/lib/src/rendering/proxy_box.dart b/packages/flutter/lib/src/rendering/proxy_box.dart
index 523f358..5a5006c 100644
--- a/packages/flutter/lib/src/rendering/proxy_box.dart
+++ b/packages/flutter/lib/src/rendering/proxy_box.dart
@@ -2,8 +2,6 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-// @dart = 2.8
-
import 'dart:async';
import 'dart:ui' as ui show ImageFilter, Gradient, Image, Color;
@@ -53,7 +51,7 @@
/// Proxy render boxes are rarely created directly because they simply proxy
/// the render box protocol to [child]. Instead, consider using one of the
/// subclasses.
- RenderProxyBox([RenderBox child]) {
+ RenderProxyBox([RenderBox? child]) {
this.child = child;
}
}
@@ -77,50 +75,50 @@
@override
double computeMinIntrinsicWidth(double height) {
if (child != null)
- return child.getMinIntrinsicWidth(height);
+ return child!.getMinIntrinsicWidth(height);
return 0.0;
}
@override
double computeMaxIntrinsicWidth(double height) {
if (child != null)
- return child.getMaxIntrinsicWidth(height);
+ return child!.getMaxIntrinsicWidth(height);
return 0.0;
}
@override
double computeMinIntrinsicHeight(double width) {
if (child != null)
- return child.getMinIntrinsicHeight(width);
+ return child!.getMinIntrinsicHeight(width);
return 0.0;
}
@override
double computeMaxIntrinsicHeight(double width) {
if (child != null)
- return child.getMaxIntrinsicHeight(width);
+ return child!.getMaxIntrinsicHeight(width);
return 0.0;
}
@override
- double computeDistanceToActualBaseline(TextBaseline baseline) {
+ double? computeDistanceToActualBaseline(TextBaseline baseline) {
if (child != null)
- return child.getDistanceToActualBaseline(baseline);
+ return child!.getDistanceToActualBaseline(baseline);
return super.computeDistanceToActualBaseline(baseline);
}
@override
void performLayout() {
if (child != null) {
- child.layout(constraints, parentUsesSize: true);
- size = child.size;
+ child!.layout(constraints, parentUsesSize: true);
+ size = child!.size;
} else {
performResize();
}
}
@override
- bool hitTestChildren(BoxHitTestResult result, { Offset position }) {
+ bool hitTestChildren(BoxHitTestResult result, { required Offset position }) {
return child?.hitTest(result, position: position) ?? false;
}
@@ -130,7 +128,7 @@
@override
void paint(PaintingContext context, Offset offset) {
if (child != null)
- context.paintChild(child, offset);
+ context.paintChild(child!, offset);
}
}
@@ -158,14 +156,14 @@
/// By default, the [behavior] is [HitTestBehavior.deferToChild].
RenderProxyBoxWithHitTestBehavior({
this.behavior = HitTestBehavior.deferToChild,
- RenderBox child,
+ RenderBox? child,
}) : super(child);
/// How to behave during hit testing.
HitTestBehavior behavior;
@override
- bool hitTest(BoxHitTestResult result, { Offset position }) {
+ bool hitTest(BoxHitTestResult result, { required Offset position }) {
bool hitTarget = false;
if (size.contains(position)) {
hitTarget = hitTestChildren(result, position: position) || hitTestSelf(position);
@@ -200,8 +198,8 @@
///
/// The [additionalConstraints] argument must not be null and must be valid.
RenderConstrainedBox({
- RenderBox child,
- @required BoxConstraints additionalConstraints,
+ RenderBox? child,
+ required BoxConstraints additionalConstraints,
}) : assert(additionalConstraints != null),
assert(additionalConstraints.debugAssertIsValid()),
_additionalConstraints = additionalConstraints,
@@ -267,8 +265,8 @@
void performLayout() {
final BoxConstraints constraints = this.constraints;
if (child != null) {
- child.layout(_additionalConstraints.enforce(constraints), parentUsesSize: true);
- size = child.size;
+ child!.layout(_additionalConstraints.enforce(constraints), parentUsesSize: true);
+ size = child!.size;
} else {
size = _additionalConstraints.enforce(constraints).constrain(Size.zero);
}
@@ -279,7 +277,7 @@
super.debugPaintSize(context, offset);
assert(() {
Paint paint;
- if (child == null || child.size.isEmpty) {
+ if (child == null || child!.size.isEmpty) {
paint = Paint()
..color = const Color(0x90909090);
context.canvas.drawRect(offset & size, paint);
@@ -314,7 +312,7 @@
/// The [maxWidth] and [maxHeight] arguments not be null and must be
/// non-negative.
RenderLimitedBox({
- RenderBox child,
+ RenderBox? child,
double maxWidth = double.infinity,
double maxHeight = double.infinity,
}) : assert(maxWidth != null && maxWidth >= 0.0),
@@ -358,8 +356,8 @@
void performLayout() {
if (child != null) {
final BoxConstraints constraints = this.constraints;
- child.layout(_limitConstraints(constraints), parentUsesSize: true);
- size = constraints.constrain(child.size);
+ child!.layout(_limitConstraints(constraints), parentUsesSize: true);
+ size = constraints.constrain(child!.size);
} else {
size = _limitConstraints(constraints).constrain(Size.zero);
}
@@ -404,8 +402,8 @@
///
/// The [aspectRatio] argument must be a finite, positive value.
RenderAspectRatio({
- RenderBox child,
- @required double aspectRatio,
+ RenderBox? child,
+ required double aspectRatio,
}) : assert(aspectRatio != null),
assert(aspectRatio > 0.0),
assert(aspectRatio.isFinite),
@@ -433,7 +431,7 @@
if (height.isFinite)
return height * _aspectRatio;
if (child != null)
- return child.getMinIntrinsicWidth(height);
+ return child!.getMinIntrinsicWidth(height);
return 0.0;
}
@@ -442,7 +440,7 @@
if (height.isFinite)
return height * _aspectRatio;
if (child != null)
- return child.getMaxIntrinsicWidth(height);
+ return child!.getMaxIntrinsicWidth(height);
return 0.0;
}
@@ -451,7 +449,7 @@
if (width.isFinite)
return width / _aspectRatio;
if (child != null)
- return child.getMinIntrinsicHeight(width);
+ return child!.getMinIntrinsicHeight(width);
return 0.0;
}
@@ -460,7 +458,7 @@
if (width.isFinite)
return width / _aspectRatio;
if (child != null)
- return child.getMaxIntrinsicHeight(width);
+ return child!.getMaxIntrinsicHeight(width);
return 0.0;
}
@@ -527,7 +525,7 @@
void performLayout() {
size = _applyAspectRatio(constraints);
if (child != null)
- child.layout(BoxConstraints.tight(size));
+ child!.layout(BoxConstraints.tight(size));
}
@override
@@ -575,9 +573,9 @@
/// If [stepWidth] is non-null it must be > 0.0. Similarly If [stepHeight] is
/// non-null it must be > 0.0.
RenderIntrinsicWidth({
- double stepWidth,
- double stepHeight,
- RenderBox child,
+ double? stepWidth,
+ double? stepHeight,
+ RenderBox? child,
}) : assert(stepWidth == null || stepWidth > 0.0),
assert(stepHeight == null || stepHeight > 0.0),
_stepWidth = stepWidth,
@@ -587,9 +585,9 @@
/// If non-null, force the child's width to be a multiple of this value.
///
/// This value must be null or > 0.0.
- double get stepWidth => _stepWidth;
- double _stepWidth;
- set stepWidth(double value) {
+ double? get stepWidth => _stepWidth;
+ double? _stepWidth;
+ set stepWidth(double? value) {
assert(value == null || value > 0.0);
if (value == _stepWidth)
return;
@@ -600,9 +598,9 @@
/// If non-null, force the child's height to be a multiple of this value.
///
/// This value must be null or > 0.0.
- double get stepHeight => _stepHeight;
- double _stepHeight;
- set stepHeight(double value) {
+ double? get stepHeight => _stepHeight;
+ double? _stepHeight;
+ set stepHeight(double? value) {
assert(value == null || value > 0.0);
if (value == _stepHeight)
return;
@@ -610,7 +608,7 @@
markNeedsLayout();
}
- static double _applyStep(double input, double step) {
+ static double _applyStep(double input, double? step) {
assert(input.isFinite);
if (step == null)
return input;
@@ -626,7 +624,7 @@
double computeMaxIntrinsicWidth(double height) {
if (child == null)
return 0.0;
- final double width = child.getMaxIntrinsicWidth(height);
+ final double width = child!.getMaxIntrinsicWidth(height);
return _applyStep(width, _stepWidth);
}
@@ -637,7 +635,7 @@
if (!width.isFinite)
width = computeMaxIntrinsicWidth(double.infinity);
assert(width.isFinite);
- final double height = child.getMinIntrinsicHeight(width);
+ final double height = child!.getMinIntrinsicHeight(width);
return _applyStep(height, _stepHeight);
}
@@ -648,7 +646,7 @@
if (!width.isFinite)
width = computeMaxIntrinsicWidth(double.infinity);
assert(width.isFinite);
- final double height = child.getMaxIntrinsicHeight(width);
+ final double height = child!.getMaxIntrinsicHeight(width);
return _applyStep(height, _stepHeight);
}
@@ -657,17 +655,17 @@
if (child != null) {
BoxConstraints childConstraints = constraints;
if (!childConstraints.hasTightWidth) {
- final double width = child.getMaxIntrinsicWidth(childConstraints.maxHeight);
+ final double width = child!.getMaxIntrinsicWidth(childConstraints.maxHeight);
assert(width.isFinite);
childConstraints = childConstraints.tighten(width: _applyStep(width, _stepWidth));
}
if (_stepHeight != null) {
- final double height = child.getMaxIntrinsicHeight(childConstraints.maxWidth);
+ final double height = child!.getMaxIntrinsicHeight(childConstraints.maxWidth);
assert(height.isFinite);
childConstraints = childConstraints.tighten(height: _applyStep(height, _stepHeight));
}
- child.layout(childConstraints, parentUsesSize: true);
- size = child.size;
+ child!.layout(childConstraints, parentUsesSize: true);
+ size = child!.size;
} else {
performResize();
}
@@ -712,7 +710,7 @@
class RenderIntrinsicHeight extends RenderProxyBox {
/// Creates a render object that sizes itself to its child's intrinsic height.
RenderIntrinsicHeight({
- RenderBox child,
+ RenderBox? child,
}) : super(child);
@override
@@ -720,9 +718,9 @@
if (child == null)
return 0.0;
if (!height.isFinite)
- height = child.getMaxIntrinsicHeight(double.infinity);
+ height = child!.getMaxIntrinsicHeight(double.infinity);
assert(height.isFinite);
- return child.getMinIntrinsicWidth(height);
+ return child!.getMinIntrinsicWidth(height);
}
@override
@@ -730,9 +728,9 @@
if (child == null)
return 0.0;
if (!height.isFinite)
- height = child.getMaxIntrinsicHeight(double.infinity);
+ height = child!.getMaxIntrinsicHeight(double.infinity);
assert(height.isFinite);
- return child.getMaxIntrinsicWidth(height);
+ return child!.getMaxIntrinsicWidth(height);
}
@override
@@ -745,12 +743,12 @@
if (child != null) {
BoxConstraints childConstraints = constraints;
if (!childConstraints.hasTightHeight) {
- final double height = child.getMaxIntrinsicHeight(childConstraints.maxWidth);
+ final double height = child!.getMaxIntrinsicHeight(childConstraints.maxWidth);
assert(height.isFinite);
childConstraints = childConstraints.tighten(height: height);
}
- child.layout(childConstraints, parentUsesSize: true);
- size = child.size;
+ child!.layout(childConstraints, parentUsesSize: true);
+ size = child!.size;
} else {
performResize();
}
@@ -774,7 +772,7 @@
RenderOpacity({
double opacity = 1.0,
bool alwaysIncludeSemantics = false,
- RenderBox child,
+ RenderBox? child,
}) : assert(opacity != null),
assert(opacity >= 0.0 && opacity <= 1.0),
assert(alwaysIncludeSemantics != null),
@@ -841,18 +839,18 @@
if (_alpha == 255) {
// No need to keep the layer. We'll create a new one if necessary.
layer = null;
- context.paintChild(child, offset);
+ context.paintChild(child!, offset);
return;
}
assert(needsCompositing);
- layer = context.pushOpacity(offset, _alpha, super.paint, oldLayer: layer as OpacityLayer);
+ layer = context.pushOpacity(offset, _alpha, super.paint, oldLayer: layer as OpacityLayer?);
}
}
@override
void visitChildrenForSemantics(RenderObjectVisitor visitor) {
if (child != null && (_alpha != 0 || alwaysIncludeSemantics))
- visitor(child);
+ visitor(child!);
}
@override
@@ -865,15 +863,15 @@
/// Implementation of [RenderAnimatedOpacity] and [RenderSliverAnimatedOpacity].
///
-/// Use this mixin in situations where the proxying behavior
-/// of [RenderProxyBox] or [RenderProxySliver] is desired for animating opacity,
-/// but would like to use the same methods for both types of render objects.
+/// This mixin allows the logic of animating opacity to be used with different
+/// layout models, e.g. the way that [RenderAnimatedOpacity] uses it for [RenderBox]
+/// and [RenderSliverAnimatedOpacity] uses it for [RenderSliver].
mixin RenderAnimatedOpacityMixin<T extends RenderObject> on RenderObjectWithChildMixin<T> {
- int _alpha;
+ int? _alpha;
@override
- bool get alwaysNeedsCompositing => child != null && _currentlyNeedsCompositing;
- bool _currentlyNeedsCompositing;
+ bool get alwaysNeedsCompositing => child != null && _currentlyNeedsCompositing!;
+ bool? _currentlyNeedsCompositing;
/// The animation that drives this render object's opacity.
///
@@ -882,17 +880,20 @@
///
/// To change the opacity of a child in a static manner, not animated,
/// consider [RenderOpacity] instead.
- Animation<double> get opacity => _opacity;
- Animation<double> _opacity;
+ ///
+ /// This getter cannot be read until the value has been set. It should be set
+ /// by the constructor of the class in which this mixin is included.
+ Animation<double> get opacity => _opacity!;
+ Animation<double>? _opacity;
set opacity(Animation<double> value) {
assert(value != null);
if (_opacity == value)
return;
if (attached && _opacity != null)
- _opacity.removeListener(_updateOpacity);
+ opacity.removeListener(_updateOpacity);
_opacity = value;
if (attached)
- _opacity.addListener(_updateOpacity);
+ opacity.addListener(_updateOpacity);
_updateOpacity();
}
@@ -901,8 +902,11 @@
/// If false, semantics are excluded when [opacity] is 0.0.
///
/// Defaults to false.
- bool get alwaysIncludeSemantics => _alwaysIncludeSemantics;
- bool _alwaysIncludeSemantics;
+ ///
+ /// This getter cannot be read until the value has been set. It should be set
+ /// by the constructor of the class in which this mixin is included.
+ bool get alwaysIncludeSemantics => _alwaysIncludeSemantics!;
+ bool? _alwaysIncludeSemantics;
set alwaysIncludeSemantics(bool value) {
if (value == _alwaysIncludeSemantics)
return;
@@ -913,22 +917,22 @@
@override
void attach(PipelineOwner owner) {
super.attach(owner);
- _opacity.addListener(_updateOpacity);
+ opacity.addListener(_updateOpacity);
_updateOpacity(); // in case it changed while we weren't listening
}
@override
void detach() {
- _opacity.removeListener(_updateOpacity);
+ opacity.removeListener(_updateOpacity);
super.detach();
}
void _updateOpacity() {
- final int oldAlpha = _alpha;
- _alpha = ui.Color.getAlphaFromOpacity(_opacity.value);
+ final int? oldAlpha = _alpha;
+ _alpha = ui.Color.getAlphaFromOpacity(opacity.value);
if (oldAlpha != _alpha) {
- final bool didNeedCompositing = _currentlyNeedsCompositing;
- _currentlyNeedsCompositing = _alpha > 0 && _alpha < 255;
+ final bool? didNeedCompositing = _currentlyNeedsCompositing;
+ _currentlyNeedsCompositing = _alpha! > 0 && _alpha! < 255;
if (child != null && didNeedCompositing != _currentlyNeedsCompositing)
markNeedsCompositingBitsUpdate();
markNeedsPaint();
@@ -948,18 +952,18 @@
if (_alpha == 255) {
// No need to keep the layer. We'll create a new one if necessary.
layer = null;
- context.paintChild(child, offset);
+ context.paintChild(child!, offset);
return;
}
assert(needsCompositing);
- layer = context.pushOpacity(offset, _alpha, super.paint, oldLayer: layer as OpacityLayer);
+ layer = context.pushOpacity(offset, _alpha!, super.paint, oldLayer: layer as OpacityLayer);
}
}
@override
void visitChildrenForSemantics(RenderObjectVisitor visitor) {
if (child != null && (_alpha != 0 || alwaysIncludeSemantics))
- visitor(child);
+ visitor(child!);
}
@override
@@ -979,9 +983,9 @@
///
/// The [opacity] argument must not be null.
RenderAnimatedOpacity({
- @required Animation<double> opacity,
+ required Animation<double> opacity,
bool alwaysIncludeSemantics = false,
- RenderBox child,
+ RenderBox? child,
}) : assert(opacity != null),
assert(alwaysIncludeSemantics != null),
super(child) {
@@ -1004,8 +1008,8 @@
///
/// The [shaderCallback] and [blendMode] arguments must not be null.
RenderShaderMask({
- RenderBox child,
- @required ShaderCallback shaderCallback,
+ RenderBox? child,
+ required ShaderCallback shaderCallback,
BlendMode blendMode = BlendMode.modulate,
}) : assert(shaderCallback != null),
assert(blendMode != null),
@@ -1014,7 +1018,7 @@
super(child);
@override
- ShaderMaskLayer get layer => super.layer as ShaderMaskLayer;
+ ShaderMaskLayer? get layer => super.layer as ShaderMaskLayer?;
/// Called to creates the [Shader] that generates the mask.
///
@@ -1057,11 +1061,11 @@
if (child != null) {
assert(needsCompositing);
layer ??= ShaderMaskLayer();
- layer
+ layer!
..shader = _shaderCallback(Offset.zero & size)
..maskRect = offset & size
..blendMode = _blendMode;
- context.pushLayer(layer, super.paint, offset);
+ context.pushLayer(layer!, super.paint, offset);
} else {
layer = null;
}
@@ -1076,13 +1080,13 @@
/// Creates a backdrop filter.
///
/// The [filter] argument must not be null.
- RenderBackdropFilter({ RenderBox child, @required ui.ImageFilter filter })
+ RenderBackdropFilter({ RenderBox? child, required ui.ImageFilter filter })
: assert(filter != null),
_filter = filter,
super(child);
@override
- BackdropFilterLayer get layer => super.layer as BackdropFilterLayer;
+ BackdropFilterLayer? get layer => super.layer as BackdropFilterLayer?;
/// The image filter to apply to the existing painted content before painting
/// the child.
@@ -1107,8 +1111,8 @@
if (child != null) {
assert(needsCompositing);
layer ??= BackdropFilterLayer();
- layer.filter = _filter;
- context.pushLayer(layer, super.paint, offset);
+ layer!.filter = _filter;
+ context.pushLayer(layer!, super.paint, offset);
} else {
layer = null;
}
@@ -1142,9 +1146,9 @@
/// Creates a custom clipper.
///
/// The clipper will update its clip whenever [reclip] notifies its listeners.
- const CustomClipper({ Listenable reclip }) : _reclip = reclip;
+ const CustomClipper({ Listenable? reclip }) : _reclip = reclip;
- final Listenable _reclip;
+ final Listenable? _reclip;
/// Register a closure to be notified when it is time to reclip.
///
@@ -1209,7 +1213,7 @@
/// of "start" and "end" instead of "left" and "right"). It may be null if
/// the border will not need the text direction to paint itself.
const ShapeBorderClipper({
- @required this.shape,
+ required this.shape,
this.textDirection,
}) : assert(shape != null);
@@ -1220,7 +1224,7 @@
///
/// [ShapeBorder]s can depend on the text direction (e.g having a "dent"
/// towards the start of the shape).
- final TextDirection textDirection;
+ final TextDirection? textDirection;
/// Returns the outer path of [shape] as the clip.
@override
@@ -1240,8 +1244,8 @@
abstract class _RenderCustomClip<T> extends RenderProxyBox {
_RenderCustomClip({
- RenderBox child,
- CustomClipper<T> clipper,
+ RenderBox? child,
+ CustomClipper<T>? clipper,
Clip clipBehavior = Clip.antiAlias,
}) : assert(clipBehavior != null),
_clipper = clipper,
@@ -1249,12 +1253,12 @@
super(child);
/// If non-null, determines which clip to use on the child.
- CustomClipper<T> get clipper => _clipper;
- CustomClipper<T> _clipper;
- set clipper(CustomClipper<T> newClipper) {
+ CustomClipper<T>? get clipper => _clipper;
+ CustomClipper<T>? _clipper;
+ set clipper(CustomClipper<T>? newClipper) {
if (_clipper == newClipper)
return;
- final CustomClipper<T> oldClipper = _clipper;
+ final CustomClipper<T>? oldClipper = _clipper;
_clipper = newClipper;
assert(newClipper != null || oldClipper != null);
if (newClipper == null || oldClipper == null ||
@@ -1287,7 +1291,7 @@
}
T get _defaultClip;
- T _clip;
+ T? _clip;
Clip get clipBehavior => _clipBehavior;
set clipBehavior(Clip value) {
@@ -1300,7 +1304,7 @@
@override
void performLayout() {
- final Size oldSize = hasSize ? size : null;
+ final Size? oldSize = hasSize ? size : null;
super.performLayout();
if (oldSize != size)
_clip = null;
@@ -1315,8 +1319,8 @@
return _clipper?.getApproximateClipRect(size) ?? Offset.zero & size;
}
- Paint _debugPaint;
- TextPainter _debugText;
+ Paint? _debugPaint;
+ TextPainter? _debugText;
@override
void debugPaintSize(PaintingContext context, Offset offset) {
assert(() {
@@ -1359,8 +1363,8 @@
///
/// The [clipBehavior] must not be null or [Clip.none].
RenderClipRect({
- RenderBox child,
- CustomClipper<Rect> clipper,
+ RenderBox? child,
+ CustomClipper<Rect>? clipper,
Clip clipBehavior = Clip.antiAlias,
}) : assert(clipBehavior != null),
assert(clipBehavior != Clip.none),
@@ -1370,11 +1374,11 @@
Rect get _defaultClip => Offset.zero & size;
@override
- bool hitTest(BoxHitTestResult result, { Offset position }) {
+ bool hitTest(BoxHitTestResult result, { required Offset position }) {
if (_clipper != null) {
_updateClip();
assert(_clip != null);
- if (!_clip.contains(position))
+ if (!_clip!.contains(position))
return false;
}
return super.hitTest(result, position: position);
@@ -1387,7 +1391,7 @@
layer = context.pushClipRect(
needsCompositing,
offset,
- _clip,
+ _clip!,
super.paint,
clipBehavior: clipBehavior,
oldLayer: layer as ClipRectLayer,
@@ -1402,8 +1406,8 @@
assert(() {
if (child != null) {
super.debugPaintSize(context, offset);
- context.canvas.drawRect(_clip.shift(offset), _debugPaint);
- _debugText.paint(context.canvas, offset + Offset(_clip.width / 8.0, -_debugText.text.style.fontSize * 1.1));
+ context.canvas.drawRect(_clip!.shift(offset), _debugPaint!);
+ _debugText!.paint(context.canvas, offset + Offset(_clip!.width / 8.0, -_debugText!.text!.style!.fontSize! * 1.1));
}
return true;
}());
@@ -1425,15 +1429,18 @@
///
/// The [clipBehavior] argument must not be null or [Clip.none].
RenderClipRRect({
- RenderBox child,
+ RenderBox? child,
BorderRadius borderRadius = BorderRadius.zero,
- CustomClipper<RRect> clipper,
+ CustomClipper<RRect>? clipper,
Clip clipBehavior = Clip.antiAlias,
}) : assert(clipBehavior != null),
assert(clipBehavior != Clip.none),
_borderRadius = borderRadius,
super(child: child, clipper: clipper, clipBehavior: clipBehavior) {
- assert(_borderRadius != null || clipper != null);
+ // `_borderRadius` has a non-nullable return type, but might be null when
+ // running with weak checking, so we need to null check it anyway (and
+ // ignore the warning that the null-handling logic is dead code).
+ assert(_borderRadius != null || clipper != null);// ignore: dead_code
}
/// The border radius of the rounded corners.
@@ -1456,11 +1463,11 @@
RRect get _defaultClip => _borderRadius.toRRect(Offset.zero & size);
@override
- bool hitTest(BoxHitTestResult result, { Offset position }) {
+ bool hitTest(BoxHitTestResult result, { required Offset position }) {
if (_clipper != null) {
_updateClip();
assert(_clip != null);
- if (!_clip.contains(position))
+ if (!_clip!.contains(position))
return false;
}
return super.hitTest(result, position: position);
@@ -1473,8 +1480,8 @@
layer = context.pushClipRRect(
needsCompositing,
offset,
- _clip.outerRect,
- _clip,
+ _clip!.outerRect,
+ _clip!,
super.paint, clipBehavior: clipBehavior, oldLayer: layer as ClipRRectLayer,
);
} else {
@@ -1487,8 +1494,8 @@
assert(() {
if (child != null) {
super.debugPaintSize(context, offset);
- context.canvas.drawRRect(_clip.shift(offset), _debugPaint);
- _debugText.paint(context.canvas, offset + Offset(_clip.tlRadiusX, -_debugText.text.style.fontSize * 1.1));
+ context.canvas.drawRRect(_clip!.shift(offset), _debugPaint!);
+ _debugText!.paint(context.canvas, offset + Offset(_clip!.tlRadiusX, -_debugText!.text!.style!.fontSize! * 1.1));
}
return true;
}());
@@ -1508,20 +1515,20 @@
///
/// The [clipBehavior] argument must not be null or [Clip.none].
RenderClipOval({
- RenderBox child,
- CustomClipper<Rect> clipper,
+ RenderBox? child,
+ CustomClipper<Rect>? clipper,
Clip clipBehavior = Clip.antiAlias,
}) : assert(clipBehavior != null),
assert(clipBehavior != Clip.none),
super(child: child, clipper: clipper, clipBehavior: clipBehavior);
- Rect _cachedRect;
- Path _cachedPath;
+ Rect? _cachedRect;
+ Path? _cachedPath;
- Path _getClipPath(Rect rect) {
+ Path? _getClipPath(Rect rect) {
if (rect != _cachedRect) {
_cachedRect = rect;
- _cachedPath = Path()..addOval(_cachedRect);
+ _cachedPath = Path()..addOval(_cachedRect!);
}
return _cachedPath;
}
@@ -1530,13 +1537,13 @@
Rect get _defaultClip => Offset.zero & size;
@override
- bool hitTest(BoxHitTestResult result, { Offset position }) {
+ bool hitTest(BoxHitTestResult result, { required Offset position }) {
_updateClip();
assert(_clip != null);
- final Offset center = _clip.center;
+ final Offset center = _clip!.center;
// convert the position to an offset from the center of the unit circle
- final Offset offset = Offset((position.dx - center.dx) / _clip.width,
- (position.dy - center.dy) / _clip.height);
+ final Offset offset = Offset((position.dx - center.dx) / _clip!.width,
+ (position.dy - center.dy) / _clip!.height);
// check if the point is outside the unit circle
if (offset.distanceSquared > 0.25) // x^2 + y^2 > r^2
return false;
@@ -1550,8 +1557,8 @@
layer = context.pushClipPath(
needsCompositing,
offset,
- _clip,
- _getClipPath(_clip),
+ _clip!,
+ _getClipPath(_clip!)!,
super.paint,
clipBehavior: clipBehavior,
oldLayer: layer as ClipPathLayer,
@@ -1566,8 +1573,8 @@
assert(() {
if (child != null) {
super.debugPaintSize(context, offset);
- context.canvas.drawPath(_getClipPath(_clip).shift(offset), _debugPaint);
- _debugText.paint(context.canvas, offset + Offset((_clip.width - _debugText.width) / 2.0, -_debugText.text.style.fontSize * 1.1));
+ context.canvas.drawPath(_getClipPath(_clip!)!.shift(offset), _debugPaint!);
+ _debugText!.paint(context.canvas, offset + Offset((_clip!.width - _debugText!.width) / 2.0, -_debugText!.text!.style!.fontSize! * 1.1));
}
return true;
}());
@@ -1595,8 +1602,8 @@
///
/// The [clipBehavior] argument must not be null or [Clip.none].
RenderClipPath({
- RenderBox child,
- CustomClipper<Path> clipper,
+ RenderBox? child,
+ CustomClipper<Path>? clipper,
Clip clipBehavior = Clip.antiAlias,
}) : assert(clipBehavior != null),
assert(clipBehavior != Clip.none),
@@ -1606,11 +1613,11 @@
Path get _defaultClip => Path()..addRect(Offset.zero & size);
@override
- bool hitTest(BoxHitTestResult result, { Offset position }) {
+ bool hitTest(BoxHitTestResult result, { required Offset position }) {
if (_clipper != null) {
_updateClip();
assert(_clip != null);
- if (!_clip.contains(position))
+ if (!_clip!.contains(position))
return false;
}
return super.hitTest(result, position: position);
@@ -1624,7 +1631,7 @@
needsCompositing,
offset,
Offset.zero & size,
- _clip,
+ _clip!,
super.paint,
clipBehavior: clipBehavior,
oldLayer: layer as ClipPathLayer,
@@ -1639,8 +1646,8 @@
assert(() {
if (child != null) {
super.debugPaintSize(context, offset);
- context.canvas.drawPath(_clip.shift(offset), _debugPaint);
- _debugText.paint(context.canvas, offset);
+ context.canvas.drawPath(_clip!.shift(offset), _debugPaint!);
+ _debugText!.paint(context.canvas, offset);
}
return true;
}());
@@ -1655,12 +1662,12 @@
/// The [shape], [elevation], [color], and [shadowColor] must not be null.
/// Additionally, the [elevation] must be non-negative.
_RenderPhysicalModelBase({
- @required RenderBox child,
- @required double elevation,
- @required Color color,
- @required Color shadowColor,
+ required RenderBox? child,
+ required double elevation,
+ required Color color,
+ required Color shadowColor,
Clip clipBehavior = Clip.none,
- CustomClipper<T> clipper,
+ CustomClipper<T>? clipper,
}) : assert(elevation != null && elevation >= 0.0),
assert(color != null),
assert(shadowColor != null),
@@ -1742,12 +1749,12 @@
/// arguments must not be null. Additionally, the [elevation] must be
/// non-negative.
RenderPhysicalModel({
- RenderBox child,
+ RenderBox? child,
BoxShape shape = BoxShape.rectangle,
Clip clipBehavior = Clip.none,
- BorderRadius borderRadius,
+ BorderRadius? borderRadius,
double elevation = 0.0,
- @required Color color,
+ required Color color,
Color shadowColor = const Color(0xFF000000),
}) : assert(shape != null),
assert(clipBehavior != null),
@@ -1765,7 +1772,7 @@
);
@override
- PhysicalModelLayer get layer => super.layer as PhysicalModelLayer;
+ PhysicalModelLayer? get layer => super.layer as PhysicalModelLayer?;
/// The shape of the layer.
///
@@ -1789,9 +1796,9 @@
/// This property is ignored if the [shape] is not [BoxShape.rectangle].
///
/// The value null is treated like [BorderRadius.zero].
- BorderRadius get borderRadius => _borderRadius;
- BorderRadius _borderRadius;
- set borderRadius(BorderRadius value) {
+ BorderRadius? get borderRadius => _borderRadius;
+ BorderRadius? _borderRadius;
+ set borderRadius(BorderRadius? value) {
if (borderRadius == value)
return;
_borderRadius = value;
@@ -1809,15 +1816,14 @@
final Rect rect = Offset.zero & size;
return RRect.fromRectXY(rect, rect.width / 2, rect.height / 2);
}
- return null;
}
@override
- bool hitTest(BoxHitTestResult result, { Offset position }) {
+ bool hitTest(BoxHitTestResult result, { required Offset position }) {
if (_clipper != null) {
_updateClip();
assert(_clip != null);
- if (!_clip.contains(position))
+ if (!_clip!.contains(position))
return false;
}
return super.hitTest(result, position: position);
@@ -1827,7 +1833,7 @@
void paint(PaintingContext context, Offset offset) {
if (child != null) {
_updateClip();
- final RRect offsetRRect = _clip.shift(offset);
+ final RRect offsetRRect = _clip!.shift(offset);
final Rect offsetBounds = offsetRRect.outerRect;
final Path offsetRRectAsPath = Path()..addRRect(offsetRRect);
bool paintShadows = true;
@@ -1847,15 +1853,15 @@
return true;
}());
layer ??= PhysicalModelLayer();
- layer
+ layer!
..clipPath = offsetRRectAsPath
..clipBehavior = clipBehavior
..elevation = paintShadows ? elevation : 0.0
..color = color
..shadowColor = shadowColor;
- context.pushLayer(layer, super.paint, offset, childPaintBounds: offsetBounds);
+ context.pushLayer(layer!, super.paint, offset, childPaintBounds: offsetBounds);
assert(() {
- layer.debugCreator = debugCreator;
+ layer!.debugCreator = debugCreator;
return true;
}());
} else {
@@ -1887,11 +1893,11 @@
/// The [clipper], [elevation], [color] and [shadowColor] must not be null.
/// Additionally, the [elevation] must be non-negative.
RenderPhysicalShape({
- RenderBox child,
- @required CustomClipper<Path> clipper,
+ RenderBox? child,
+ required CustomClipper<Path> clipper,
Clip clipBehavior = Clip.none,
double elevation = 0.0,
- @required Color color,
+ required Color color,
Color shadowColor = const Color(0xFF000000),
}) : assert(clipper != null),
assert(elevation != null && elevation >= 0.0),
@@ -1907,17 +1913,17 @@
);
@override
- PhysicalModelLayer get layer => super.layer as PhysicalModelLayer;
+ PhysicalModelLayer? get layer => super.layer as PhysicalModelLayer?;
@override
Path get _defaultClip => Path()..addRect(Offset.zero & size);
@override
- bool hitTest(BoxHitTestResult result, { Offset position }) {
+ bool hitTest(BoxHitTestResult result, { required Offset position }) {
if (_clipper != null) {
_updateClip();
assert(_clip != null);
- if (!_clip.contains(position))
+ if (!_clip!.contains(position))
return false;
}
return super.hitTest(result, position: position);
@@ -1928,7 +1934,7 @@
if (child != null) {
_updateClip();
final Rect offsetBounds = offset & size;
- final Path offsetPath = _clip.shift(offset);
+ final Path offsetPath = _clip!.shift(offset);
bool paintShadows = true;
assert(() {
if (debugDisableShadows) {
@@ -1946,15 +1952,15 @@
return true;
}());
layer ??= PhysicalModelLayer();
- layer
+ layer!
..clipPath = offsetPath
..clipBehavior = clipBehavior
..elevation = paintShadows ? elevation : 0.0
..color = color
..shadowColor = shadowColor;
- context.pushLayer(layer, super.paint, offset, childPaintBounds: offsetBounds);
+ context.pushLayer(layer!, super.paint, offset, childPaintBounds: offsetBounds);
assert(() {
- layer.debugCreator = debugCreator;
+ layer!.debugCreator = debugCreator;
return true;
}());
} else {
@@ -1988,10 +1994,10 @@
/// The [ImageConfiguration] will be passed to the decoration (with the size
/// filled in) to let it resolve images.
RenderDecoratedBox({
- @required Decoration decoration,
+ required Decoration decoration,
DecorationPosition position = DecorationPosition.background,
ImageConfiguration configuration = ImageConfiguration.empty,
- RenderBox child,
+ RenderBox? child,
}) : assert(decoration != null),
assert(position != null),
assert(configuration != null),
@@ -2000,7 +2006,7 @@
_configuration = configuration,
super(child);
- BoxPainter _painter;
+ BoxPainter? _painter;
/// What decoration to paint.
///
@@ -2069,12 +2075,12 @@
_painter ??= _decoration.createBoxPainter(markNeedsPaint);
final ImageConfiguration filledConfiguration = configuration.copyWith(size: size);
if (position == DecorationPosition.background) {
- int debugSaveCount;
+ int? debugSaveCount;
assert(() {
debugSaveCount = context.canvas.getSaveCount();
return true;
}());
- _painter.paint(context.canvas, offset, filledConfiguration);
+ _painter!.paint(context.canvas, offset, filledConfiguration);
assert(() {
if (debugSaveCount != context.canvas.getSaveCount()) {
throw FlutterError.fromParts(<DiagnosticsNode>[
@@ -2095,7 +2101,7 @@
}
super.paint(context, offset);
if (position == DecorationPosition.foreground) {
- _painter.paint(context.canvas, offset, filledConfiguration);
+ _painter!.paint(context.canvas, offset, filledConfiguration);
if (decoration.isComplex)
context.setIsComplexHint();
}
@@ -2115,12 +2121,12 @@
///
/// The [transform] argument must not be null.
RenderTransform({
- @required Matrix4 transform,
- Offset origin,
- AlignmentGeometry alignment,
- TextDirection textDirection,
+ required Matrix4 transform,
+ Offset? origin,
+ AlignmentGeometry? alignment,
+ TextDirection? textDirection,
this.transformHitTests = true,
- RenderBox child,
+ RenderBox? child,
}) : assert(transform != null),
super(child) {
this.transform = transform;
@@ -2134,9 +2140,9 @@
///
/// Setting an origin is equivalent to conjugating the transform matrix by a
/// translation. This property is provided just for convenience.
- Offset get origin => _origin;
- Offset _origin;
- set origin(Offset value) {
+ Offset? get origin => _origin;
+ Offset? _origin;
+ set origin(Offset? value) {
if (_origin == value)
return;
_origin = value;
@@ -2155,9 +2161,9 @@
/// Similarly [AlignmentDirectional.centerEnd] is the same as an [Alignment]
/// whose [Alignment.x] value is `1.0` if [textDirection] is
/// [TextDirection.ltr], and `-1.0` if [textDirection] is [TextDirection.rtl].
- AlignmentGeometry get alignment => _alignment;
- AlignmentGeometry _alignment;
- set alignment(AlignmentGeometry value) {
+ AlignmentGeometry? get alignment => _alignment;
+ AlignmentGeometry? _alignment;
+ set alignment(AlignmentGeometry? value) {
if (_alignment == value)
return;
_alignment = value;
@@ -2169,9 +2175,9 @@
///
/// This may be changed to null, but only after [alignment] has been changed
/// to a value that does not depend on the direction.
- TextDirection get textDirection => _textDirection;
- TextDirection _textDirection;
- set textDirection(TextDirection value) {
+ TextDirection? get textDirection => _textDirection;
+ TextDirection? _textDirection;
+ set textDirection(TextDirection? value) {
if (_textDirection == value)
return;
_textDirection = value;
@@ -2188,7 +2194,7 @@
bool transformHitTests;
// Note the lack of a getter for transform because Matrix4 is not immutable
- Matrix4 _transform;
+ Matrix4? _transform;
/// The matrix to transform the child by during painting.
set transform(Matrix4 value) {
@@ -2202,68 +2208,68 @@
/// Sets the transform to the identity matrix.
void setIdentity() {
- _transform.setIdentity();
+ _transform!.setIdentity();
markNeedsPaint();
markNeedsSemanticsUpdate();
}
/// Concatenates a rotation about the x axis into the transform.
void rotateX(double radians) {
- _transform.rotateX(radians);
+ _transform!.rotateX(radians);
markNeedsPaint();
markNeedsSemanticsUpdate();
}
/// Concatenates a rotation about the y axis into the transform.
void rotateY(double radians) {
- _transform.rotateY(radians);
+ _transform!.rotateY(radians);
markNeedsPaint();
markNeedsSemanticsUpdate();
}
/// Concatenates a rotation about the z axis into the transform.
void rotateZ(double radians) {
- _transform.rotateZ(radians);
+ _transform!.rotateZ(radians);
markNeedsPaint();
markNeedsSemanticsUpdate();
}
/// Concatenates a translation by (x, y, z) into the transform.
void translate(double x, [ double y = 0.0, double z = 0.0 ]) {
- _transform.translate(x, y, z);
+ _transform!.translate(x, y, z);
markNeedsPaint();
markNeedsSemanticsUpdate();
}
/// Concatenates a scale into the transform.
- void scale(double x, [ double y, double z ]) {
- _transform.scale(x, y, z);
+ void scale(double x, [ double? y, double? z ]) {
+ _transform!.scale(x, y, z);
markNeedsPaint();
markNeedsSemanticsUpdate();
}
- Matrix4 get _effectiveTransform {
- final Alignment resolvedAlignment = alignment?.resolve(textDirection);
+ Matrix4? get _effectiveTransform {
+ final Alignment? resolvedAlignment = alignment?.resolve(textDirection);
if (_origin == null && resolvedAlignment == null)
return _transform;
final Matrix4 result = Matrix4.identity();
if (_origin != null)
- result.translate(_origin.dx, _origin.dy);
- Offset translation;
+ result.translate(_origin!.dx, _origin!.dy);
+ Offset? translation;
if (resolvedAlignment != null) {
translation = resolvedAlignment.alongSize(size);
result.translate(translation.dx, translation.dy);
}
- result.multiply(_transform);
+ result.multiply(_transform!);
if (resolvedAlignment != null)
- result.translate(-translation.dx, -translation.dy);
+ result.translate(-translation!.dx, -translation.dy);
if (_origin != null)
- result.translate(-_origin.dx, -_origin.dy);
+ result.translate(-_origin!.dx, -_origin!.dy);
return result;
}
@override
- bool hitTest(BoxHitTestResult result, { Offset position }) {
+ bool hitTest(BoxHitTestResult result, { required Offset position }) {
// RenderTransform objects don't check if they are
// themselves hit, because it's confusing to think about
// how the untransformed size and the child's transformed
@@ -2272,13 +2278,13 @@
}
@override
- bool hitTestChildren(BoxHitTestResult result, { Offset position }) {
+ bool hitTestChildren(BoxHitTestResult result, { required Offset position }) {
assert(!transformHitTests || _effectiveTransform != null);
return result.addWithPaintTransform(
transform: transformHitTests ? _effectiveTransform : null,
position: position,
- hitTest: (BoxHitTestResult result, Offset position) {
- return super.hitTestChildren(result, position: position);
+ hitTest: (BoxHitTestResult result, Offset? position) {
+ return super.hitTestChildren(result, position: position!);
},
);
}
@@ -2286,8 +2292,8 @@
@override
void paint(PaintingContext context, Offset offset) {
if (child != null) {
- final Matrix4 transform = _effectiveTransform;
- final Offset childOffset = MatrixUtils.getAsTranslation(transform);
+ final Matrix4 transform = _effectiveTransform!;
+ final Offset? childOffset = MatrixUtils.getAsTranslation(transform);
if (childOffset == null) {
layer = context.pushTransform(
needsCompositing,
@@ -2305,7 +2311,7 @@
@override
void applyPaintTransform(RenderBox child, Matrix4 transform) {
- transform.multiply(_effectiveTransform);
+ transform.multiply(_effectiveTransform!);
}
@override
@@ -2327,8 +2333,8 @@
RenderFittedBox({
BoxFit fit = BoxFit.contain,
AlignmentGeometry alignment = Alignment.center,
- TextDirection textDirection,
- RenderBox child,
+ TextDirection? textDirection,
+ RenderBox? child,
Clip clipBehavior = Clip.none,
}) : assert(fit != null),
assert(alignment != null),
@@ -2339,7 +2345,7 @@
_clipBehavior = clipBehavior,
super(child);
- Alignment _resolvedAlignment;
+ Alignment? _resolvedAlignment;
void _resolve() {
if (_resolvedAlignment != null)
@@ -2401,9 +2407,9 @@
///
/// This may be changed to null, but only after [alignment] has been changed
/// to a value that does not depend on the direction.
- TextDirection get textDirection => _textDirection;
- TextDirection _textDirection;
- set textDirection(TextDirection value) {
+ TextDirection? get textDirection => _textDirection;
+ TextDirection? _textDirection;
+ set textDirection(TextDirection? value) {
if (_textDirection == value)
return;
_textDirection = value;
@@ -2416,15 +2422,15 @@
@override
void performLayout() {
if (child != null) {
- child.layout(const BoxConstraints(), parentUsesSize: true);
+ child!.layout(const BoxConstraints(), parentUsesSize: true);
switch (fit) {
case BoxFit.scaleDown:
final BoxConstraints sizeConstraints = constraints.loosen();
- final Size unconstrainedSize = sizeConstraints.constrainSizeAndAttemptToPreserveAspectRatio(child.size);
+ final Size unconstrainedSize = sizeConstraints.constrainSizeAndAttemptToPreserveAspectRatio(child!.size);
size = constraints.constrain(unconstrainedSize);
break;
default:
- size = constraints.constrainSizeAndAttemptToPreserveAspectRatio(child.size);
+ size = constraints.constrainSizeAndAttemptToPreserveAspectRatio(child!.size);
break;
}
_clearPaintData();
@@ -2433,8 +2439,8 @@
}
}
- bool _hasVisualOverflow;
- Matrix4 _transform;
+ bool? _hasVisualOverflow;
+ Matrix4? _transform;
/// {@macro flutter.widgets.Clip}
///
@@ -2464,25 +2470,25 @@
_transform = Matrix4.identity();
} else {
_resolve();
- final Size childSize = child.size;
+ final Size childSize = child!.size;
final FittedSizes sizes = applyBoxFit(_fit, childSize, size);
final double scaleX = sizes.destination.width / sizes.source.width;
final double scaleY = sizes.destination.height / sizes.source.height;
- final Rect sourceRect = _resolvedAlignment.inscribe(sizes.source, Offset.zero & childSize);
- final Rect destinationRect = _resolvedAlignment.inscribe(sizes.destination, Offset.zero & size);
+ final Rect sourceRect = _resolvedAlignment!.inscribe(sizes.source, Offset.zero & childSize);
+ final Rect destinationRect = _resolvedAlignment!.inscribe(sizes.destination, Offset.zero & size);
_hasVisualOverflow = sourceRect.width < childSize.width || sourceRect.height < childSize.height;
assert(scaleX.isFinite && scaleY.isFinite);
_transform = Matrix4.translationValues(destinationRect.left, destinationRect.top, 0.0)
..scale(scaleX, scaleY, 1.0)
..translate(-sourceRect.left, -sourceRect.top);
- assert(_transform.storage.every((double value) => value.isFinite));
+ assert(_transform!.storage.every((double value) => value.isFinite));
}
}
- TransformLayer _paintChildWithTransform(PaintingContext context, Offset offset) {
- final Offset childOffset = MatrixUtils.getAsTranslation(_transform);
+ TransformLayer? _paintChildWithTransform(PaintingContext context, Offset offset) {
+ final Offset? childOffset = MatrixUtils.getAsTranslation(_transform!);
if (childOffset == null)
- return context.pushTransform(needsCompositing, offset, _transform, super.paint,
+ return context.pushTransform(needsCompositing, offset, _transform!, super.paint,
oldLayer: layer is TransformLayer ? layer as TransformLayer : null);
else
super.paint(context, offset + childOffset);
@@ -2491,11 +2497,11 @@
@override
void paint(PaintingContext context, Offset offset) {
- if (size.isEmpty || child.size.isEmpty)
+ if (size.isEmpty || child!.size.isEmpty)
return;
_updatePaintData();
if (child != null) {
- if (_hasVisualOverflow && clipBehavior != Clip.none)
+ if (_hasVisualOverflow! && clipBehavior != Clip.none)
layer = context.pushClipRect(needsCompositing, offset, Offset.zero & size, _paintChildWithTransform,
oldLayer: layer is ClipRectLayer ? layer as ClipRectLayer : null, clipBehavior: clipBehavior);
else
@@ -2504,15 +2510,15 @@
}
@override
- bool hitTestChildren(BoxHitTestResult result, { Offset position }) {
- if (size.isEmpty || child?.size?.isEmpty == true)
+ bool hitTestChildren(BoxHitTestResult result, { required Offset position }) {
+ if (size.isEmpty || child?.size.isEmpty == true)
return false;
_updatePaintData();
return result.addWithPaintTransform(
transform: _transform,
position: position,
- hitTest: (BoxHitTestResult result, Offset position) {
- return super.hitTestChildren(result, position: position);
+ hitTest: (BoxHitTestResult result, Offset? position) {
+ return super.hitTestChildren(result, position: position!);
},
);
}
@@ -2523,7 +2529,7 @@
transform.setZero();
} else {
_updatePaintData();
- transform.multiply(_transform);
+ transform.multiply(_transform!);
}
}
@@ -2550,9 +2556,9 @@
///
/// The [translation] argument must not be null.
RenderFractionalTranslation({
- @required Offset translation,
+ required Offset translation,
this.transformHitTests = true,
- RenderBox child,
+ RenderBox? child,
}) : assert(translation != null),
_translation = translation,
super(child);
@@ -2573,7 +2579,7 @@
}
@override
- bool hitTest(BoxHitTestResult result, { Offset position }) {
+ bool hitTest(BoxHitTestResult result, { required Offset position }) {
// RenderFractionalTranslation objects don't check if they are
// themselves hit, because it's confusing to think about
// how the untransformed size and the child's transformed
@@ -2590,15 +2596,15 @@
bool transformHitTests;
@override
- bool hitTestChildren(BoxHitTestResult result, { Offset position }) {
+ bool hitTestChildren(BoxHitTestResult result, { required Offset position }) {
assert(!debugNeedsLayout);
return result.addWithPaintOffset(
offset: transformHitTests
? Offset(translation.dx * size.width, translation.dy * size.height)
: null,
position: position,
- hitTest: (BoxHitTestResult result, Offset position) {
- return super.hitTestChildren(result, position: position);
+ hitTest: (BoxHitTestResult result, Offset? position) {
+ return super.hitTestChildren(result, position: position!);
},
);
}
@@ -2678,27 +2684,27 @@
this.onPointerCancel,
this.onPointerSignal,
HitTestBehavior behavior = HitTestBehavior.deferToChild,
- RenderBox child,
+ RenderBox? child,
}) : super(behavior: behavior, child: child);
/// Called when a pointer comes into contact with the screen (for touch
/// pointers), or has its button pressed (for mouse pointers) at this widget's
/// location.
- PointerDownEventListener onPointerDown;
+ PointerDownEventListener? onPointerDown;
/// Called when a pointer that triggered an [onPointerDown] changes position.
- PointerMoveEventListener onPointerMove;
+ PointerMoveEventListener? onPointerMove;
/// Called when a pointer that triggered an [onPointerDown] is no longer in
/// contact with the screen.
- PointerUpEventListener onPointerUp;
+ PointerUpEventListener? onPointerUp;
/// Called when the input from a pointer that triggered an [onPointerDown] is
/// no longer directed towards this receiver.
- PointerCancelEventListener onPointerCancel;
+ PointerCancelEventListener? onPointerCancel;
/// Called when a pointer signal occurs over this object.
- PointerSignalEventListener onPointerSignal;
+ PointerSignalEventListener? onPointerSignal;
@override
void performResize() {
@@ -2709,23 +2715,23 @@
void handleEvent(PointerEvent event, HitTestEntry entry) {
assert(debugHandleEvent(event, entry));
if (onPointerDown != null && event is PointerDownEvent)
- return onPointerDown(event);
+ return onPointerDown!(event);
if (onPointerMove != null && event is PointerMoveEvent)
- return onPointerMove(event);
+ return onPointerMove!(event);
if (onPointerUp != null && event is PointerUpEvent)
- return onPointerUp(event);
+ return onPointerUp!(event);
if (onPointerCancel != null && event is PointerCancelEvent)
- return onPointerCancel(event);
+ return onPointerCancel!(event);
if (onPointerSignal != null && event is PointerSignalEvent)
- return onPointerSignal(event);
+ return onPointerSignal!(event);
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
- properties.add(FlagsSummary<Function>(
+ properties.add(FlagsSummary<Function?>(
'listeners',
- <String, Function>{
+ <String, Function?>{
'down': onPointerDown,
'move': onPointerMove,
'up': onPointerUp,
@@ -2767,7 +2773,7 @@
this.onExit,
MouseCursor cursor = MouseCursor.defer,
bool opaque = true,
- RenderBox child,
+ RenderBox? child,
}) : assert(opaque != null),
assert(cursor != null),
_cursor = cursor,
@@ -2779,7 +2785,7 @@
bool hitTestSelf(Offset position) => true;
@override
- bool hitTest(BoxHitTestResult result, { @required Offset position }) {
+ bool hitTest(BoxHitTestResult result, { required Offset position }) {
return super.hitTest(result, position: position) && _opaque;
}
@@ -2787,7 +2793,7 @@
void handleEvent(PointerEvent event, HitTestEntry entry) {
assert(debugHandleEvent(event, entry));
if (onHover != null && event is PointerHoverEvent)
- return onHover(event);
+ return onHover!(event);
}
/// Whether this object should prevent [RenderMouseRegion]s visually behind it
@@ -2815,13 +2821,13 @@
}
@override
- PointerEnterEventListener onEnter;
+ PointerEnterEventListener? onEnter;
@override
- PointerHoverEventListener onHover;
+ PointerHoverEventListener? onHover;
@override
- PointerExitEventListener onExit;
+ PointerExitEventListener? onExit;
@override
MouseCursor get cursor => _cursor;
@@ -2843,9 +2849,9 @@
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
- properties.add(FlagsSummary<Function>(
+ properties.add(FlagsSummary<Function?>(
'listeners',
- <String, Function>{
+ <String, Function?>{
'enter': onEnter,
'hover': onHover,
'exit': onExit,
@@ -2884,7 +2890,7 @@
/// [debugAsymmetricPaintCount] and [debugSymmetricPaintCount] respectively.
class RenderRepaintBoundary extends RenderProxyBox {
/// Creates a repaint boundary around [child].
- RenderRepaintBoundary({ RenderBox child }) : super(child);
+ RenderRepaintBoundary({ RenderBox? child }) : super(child);
@override
bool get isRepaintBoundary => true;
@@ -3065,9 +3071,9 @@
/// The [ignoring] argument must not be null. If [ignoringSemantics] is null,
/// this render object will be ignored for semantics if [ignoring] is true.
RenderIgnorePointer({
- RenderBox child,
+ RenderBox? child,
bool ignoring = true,
- bool ignoringSemantics,
+ bool? ignoringSemantics,
}) : _ignoring = ignoring,
_ignoringSemantics = ignoringSemantics,
super(child) {
@@ -3085,7 +3091,7 @@
if (value == _ignoring)
return;
_ignoring = value;
- if (_ignoringSemantics == null || !_ignoringSemantics)
+ if (_ignoringSemantics == null || !_ignoringSemantics!)
markNeedsSemanticsUpdate();
}
@@ -3094,9 +3100,9 @@
/// If null, defaults to value of [ignoring].
///
/// See [SemanticsNode] for additional information about the semantics tree.
- bool get ignoringSemantics => _ignoringSemantics;
- bool _ignoringSemantics;
- set ignoringSemantics(bool value) {
+ bool? get ignoringSemantics => _ignoringSemantics;
+ bool? _ignoringSemantics;
+ set ignoringSemantics(bool? value) {
if (value == _ignoringSemantics)
return;
final bool oldEffectiveValue = _effectiveIgnoringSemantics;
@@ -3108,7 +3114,7 @@
bool get _effectiveIgnoringSemantics => ignoringSemantics ?? ignoring;
@override
- bool hitTest(BoxHitTestResult result, { Offset position }) {
+ bool hitTest(BoxHitTestResult result, { required Offset position }) {
return !ignoring && super.hitTest(result, position: position);
}
@@ -3118,7 +3124,7 @@
@override
void visitChildrenForSemantics(RenderObjectVisitor visitor) {
if (child != null && !_effectiveIgnoringSemantics)
- visitor(child);
+ visitor(child!);
}
@override
@@ -3142,7 +3148,7 @@
/// Creates an offstage render object.
RenderOffstage({
bool offstage = true,
- RenderBox child,
+ RenderBox? child,
}) : assert(offstage != null),
_offstage = offstage,
super(child);
@@ -3193,7 +3199,7 @@
}
@override
- double computeDistanceToActualBaseline(TextBaseline baseline) {
+ double? computeDistanceToActualBaseline(TextBaseline baseline) {
if (offstage)
return null;
return super.computeDistanceToActualBaseline(baseline);
@@ -3218,7 +3224,7 @@
}
@override
- bool hitTest(BoxHitTestResult result, { Offset position }) {
+ bool hitTest(BoxHitTestResult result, { required Offset position }) {
return !offstage && super.hitTest(result, position: position);
}
@@ -3247,7 +3253,7 @@
if (child == null)
return <DiagnosticsNode>[];
return <DiagnosticsNode>[
- child.toDiagnosticsNode(
+ child!.toDiagnosticsNode(
name: 'child',
style: offstage ? DiagnosticsTreeStyle.offstage : DiagnosticsTreeStyle.sparse,
),
@@ -3272,9 +3278,9 @@
///
/// The [absorbing] argument must not be null.
RenderAbsorbPointer({
- RenderBox child,
+ RenderBox? child,
bool absorbing = true,
- bool ignoringSemantics,
+ bool? ignoringSemantics,
}) : assert(absorbing != null),
_absorbing = absorbing,
_ignoringSemantics = ignoringSemantics,
@@ -3300,9 +3306,9 @@
/// If null, defaults to value of [absorbing].
///
/// See [SemanticsNode] for additional information about the semantics tree.
- bool get ignoringSemantics => _ignoringSemantics;
- bool _ignoringSemantics;
- set ignoringSemantics(bool value) {
+ bool? get ignoringSemantics => _ignoringSemantics;
+ bool? _ignoringSemantics;
+ set ignoringSemantics(bool? value) {
if (value == _ignoringSemantics)
return;
final bool oldEffectiveValue = _effectiveIgnoringSemantics;
@@ -3314,7 +3320,7 @@
bool get _effectiveIgnoringSemantics => ignoringSemantics ?? absorbing;
@override
- bool hitTest(BoxHitTestResult result, { Offset position }) {
+ bool hitTest(BoxHitTestResult result, { required Offset position }) {
return absorbing
? size.contains(position)
: super.hitTest(result, position: position);
@@ -3323,7 +3329,7 @@
@override
void visitChildrenForSemantics(RenderObjectVisitor visitor) {
if (child != null && !_effectiveIgnoringSemantics)
- visitor(child);
+ visitor(child!);
}
@override
@@ -3353,7 +3359,7 @@
RenderMetaData({
this.metaData,
HitTestBehavior behavior = HitTestBehavior.deferToChild,
- RenderBox child,
+ RenderBox? child,
}) : super(behavior: behavior, child: child);
/// Opaque meta data ignored by the render tree.
@@ -3373,11 +3379,11 @@
///
/// The [scrollFactor] argument must not be null.
RenderSemanticsGestureHandler({
- RenderBox child,
- GestureTapCallback onTap,
- GestureLongPressCallback onLongPress,
- GestureDragUpdateCallback onHorizontalDragUpdate,
- GestureDragUpdateCallback onVerticalDragUpdate,
+ RenderBox? child,
+ GestureTapCallback? onTap,
+ GestureLongPressCallback? onLongPress,
+ GestureDragUpdateCallback? onHorizontalDragUpdate,
+ GestureDragUpdateCallback? onVerticalDragUpdate,
this.scrollFactor = 0.8,
}) : assert(scrollFactor != null),
_onTap = onTap,
@@ -3399,9 +3405,9 @@
/// if [onHorizontalDragUpdate] is set but [validActions] only contains
/// [SemanticsAction.scrollLeft], then the [SemanticsAction.scrollRight]
/// action will be omitted.
- Set<SemanticsAction> get validActions => _validActions;
- Set<SemanticsAction> _validActions;
- set validActions(Set<SemanticsAction> value) {
+ Set<SemanticsAction>? get validActions => _validActions;
+ Set<SemanticsAction>? _validActions;
+ set validActions(Set<SemanticsAction>? value) {
if (setEquals<SemanticsAction>(value, _validActions))
return;
_validActions = value;
@@ -3409,9 +3415,9 @@
}
/// Called when the user taps on the render object.
- GestureTapCallback get onTap => _onTap;
- GestureTapCallback _onTap;
- set onTap(GestureTapCallback value) {
+ GestureTapCallback? get onTap => _onTap;
+ GestureTapCallback? _onTap;
+ set onTap(GestureTapCallback? value) {
if (_onTap == value)
return;
final bool hadHandler = _onTap != null;
@@ -3421,9 +3427,9 @@
}
/// Called when the user presses on the render object for a long period of time.
- GestureLongPressCallback get onLongPress => _onLongPress;
- GestureLongPressCallback _onLongPress;
- set onLongPress(GestureLongPressCallback value) {
+ GestureLongPressCallback? get onLongPress => _onLongPress;
+ GestureLongPressCallback? _onLongPress;
+ set onLongPress(GestureLongPressCallback? value) {
if (_onLongPress == value)
return;
final bool hadHandler = _onLongPress != null;
@@ -3433,9 +3439,9 @@
}
/// Called when the user scrolls to the left or to the right.
- GestureDragUpdateCallback get onHorizontalDragUpdate => _onHorizontalDragUpdate;
- GestureDragUpdateCallback _onHorizontalDragUpdate;
- set onHorizontalDragUpdate(GestureDragUpdateCallback value) {
+ GestureDragUpdateCallback? get onHorizontalDragUpdate => _onHorizontalDragUpdate;
+ GestureDragUpdateCallback? _onHorizontalDragUpdate;
+ set onHorizontalDragUpdate(GestureDragUpdateCallback? value) {
if (_onHorizontalDragUpdate == value)
return;
final bool hadHandler = _onHorizontalDragUpdate != null;
@@ -3445,9 +3451,9 @@
}
/// Called when the user scrolls up or down.
- GestureDragUpdateCallback get onVerticalDragUpdate => _onVerticalDragUpdate;
- GestureDragUpdateCallback _onVerticalDragUpdate;
- set onVerticalDragUpdate(GestureDragUpdateCallback value) {
+ GestureDragUpdateCallback? get onVerticalDragUpdate => _onVerticalDragUpdate;
+ GestureDragUpdateCallback? _onVerticalDragUpdate;
+ set onVerticalDragUpdate(GestureDragUpdateCallback? value) {
if (_onVerticalDragUpdate == value)
return;
final bool hadHandler = _onVerticalDragUpdate != null;
@@ -3486,13 +3492,13 @@
}
bool _isValidAction(SemanticsAction action) {
- return validActions == null || validActions.contains(action);
+ return validActions == null || validActions!.contains(action);
}
void _performSemanticScrollLeft() {
if (onHorizontalDragUpdate != null) {
final double primaryDelta = size.width * -scrollFactor;
- onHorizontalDragUpdate(DragUpdateDetails(
+ onHorizontalDragUpdate!(DragUpdateDetails(
delta: Offset(primaryDelta, 0.0), primaryDelta: primaryDelta,
globalPosition: localToGlobal(size.center(Offset.zero)),
));
@@ -3502,7 +3508,7 @@
void _performSemanticScrollRight() {
if (onHorizontalDragUpdate != null) {
final double primaryDelta = size.width * scrollFactor;
- onHorizontalDragUpdate(DragUpdateDetails(
+ onHorizontalDragUpdate!(DragUpdateDetails(
delta: Offset(primaryDelta, 0.0), primaryDelta: primaryDelta,
globalPosition: localToGlobal(size.center(Offset.zero)),
));
@@ -3512,7 +3518,7 @@
void _performSemanticScrollUp() {
if (onVerticalDragUpdate != null) {
final double primaryDelta = size.height * -scrollFactor;
- onVerticalDragUpdate(DragUpdateDetails(
+ onVerticalDragUpdate!(DragUpdateDetails(
delta: Offset(0.0, primaryDelta), primaryDelta: primaryDelta,
globalPosition: localToGlobal(size.center(Offset.zero)),
));
@@ -3522,7 +3528,7 @@
void _performSemanticScrollDown() {
if (onVerticalDragUpdate != null) {
final double primaryDelta = size.height * scrollFactor;
- onVerticalDragUpdate(DragUpdateDetails(
+ onVerticalDragUpdate!(DragUpdateDetails(
delta: Offset(0.0, primaryDelta), primaryDelta: primaryDelta,
globalPosition: localToGlobal(size.center(Offset.zero)),
));
@@ -3552,59 +3558,59 @@
///
/// If the [label] is not null, the [textDirection] must also not be null.
RenderSemanticsAnnotations({
- RenderBox child,
+ RenderBox? child,
bool container = false,
bool explicitChildNodes = false,
bool excludeSemantics = false,
- bool enabled,
- bool checked,
- bool toggled,
- bool selected,
- bool button,
- bool link,
- bool header,
- bool textField,
- bool readOnly,
- bool focusable,
- bool focused,
- bool inMutuallyExclusiveGroup,
- bool obscured,
- bool multiline,
- bool scopesRoute,
- bool namesRoute,
- bool hidden,
- bool image,
- bool liveRegion,
- int maxValueLength,
- int currentValueLength,
- String label,
- String value,
- String increasedValue,
- String decreasedValue,
- String hint,
- SemanticsHintOverrides hintOverrides,
- TextDirection textDirection,
- SemanticsSortKey sortKey,
- VoidCallback onTap,
- VoidCallback onDismiss,
- VoidCallback onLongPress,
- VoidCallback onScrollLeft,
- VoidCallback onScrollRight,
- VoidCallback onScrollUp,
- VoidCallback onScrollDown,
- VoidCallback onIncrease,
- VoidCallback onDecrease,
- VoidCallback onCopy,
- VoidCallback onCut,
- VoidCallback onPaste,
- MoveCursorHandler onMoveCursorForwardByCharacter,
- MoveCursorHandler onMoveCursorBackwardByCharacter,
- MoveCursorHandler onMoveCursorForwardByWord,
- MoveCursorHandler onMoveCursorBackwardByWord,
- SetSelectionHandler onSetSelection,
- VoidCallback onDidGainAccessibilityFocus,
- VoidCallback onDidLoseAccessibilityFocus,
- Map<CustomSemanticsAction, VoidCallback> customSemanticsActions,
+ bool? enabled,
+ bool? checked,
+ bool? toggled,
+ bool? selected,
+ bool? button,
+ bool? link,
+ bool? header,
+ bool? textField,
+ bool? readOnly,
+ bool? focusable,
+ bool? focused,
+ bool? inMutuallyExclusiveGroup,
+ bool? obscured,
+ bool? multiline,
+ bool? scopesRoute,
+ bool? namesRoute,
+ bool? hidden,
+ bool? image,
+ bool? liveRegion,
+ int? maxValueLength,
+ int? currentValueLength,
+ String? label,
+ String? value,
+ String? increasedValue,
+ String? decreasedValue,
+ String? hint,
+ SemanticsHintOverrides? hintOverrides,
+ TextDirection? textDirection,
+ SemanticsSortKey? sortKey,
+ VoidCallback? onTap,
+ VoidCallback? onDismiss,
+ VoidCallback? onLongPress,
+ VoidCallback? onScrollLeft,
+ VoidCallback? onScrollRight,
+ VoidCallback? onScrollUp,
+ VoidCallback? onScrollDown,
+ VoidCallback? onIncrease,
+ VoidCallback? onDecrease,
+ VoidCallback? onCopy,
+ VoidCallback? onCut,
+ VoidCallback? onPaste,
+ MoveCursorHandler? onMoveCursorForwardByCharacter,
+ MoveCursorHandler? onMoveCursorBackwardByCharacter,
+ MoveCursorHandler? onMoveCursorForwardByWord,
+ MoveCursorHandler? onMoveCursorBackwardByWord,
+ SetSelectionHandler? onSetSelection,
+ VoidCallback? onDidGainAccessibilityFocus,
+ VoidCallback? onDidLoseAccessibilityFocus,
+ Map<CustomSemanticsAction, VoidCallback>? customSemanticsActions,
}) : assert(container != null),
_container = container,
_explicitChildNodes = explicitChildNodes,
@@ -3718,9 +3724,9 @@
/// If non-null, sets the [SemanticsFlag.hasCheckedState] semantic to true and
/// the [SemanticsConfiguration.isChecked] semantic to the given value.
- bool get checked => _checked;
- bool _checked;
- set checked(bool value) {
+ bool? get checked => _checked;
+ bool? _checked;
+ set checked(bool? value) {
if (checked == value)
return;
_checked = value;
@@ -3729,9 +3735,9 @@
/// If non-null, sets the [SemanticsFlag.hasEnabledState] semantic to true and
/// the [SemanticsConfiguration.isEnabled] semantic to the given value.
- bool get enabled => _enabled;
- bool _enabled;
- set enabled(bool value) {
+ bool? get enabled => _enabled;
+ bool? _enabled;
+ set enabled(bool? value) {
if (enabled == value)
return;
_enabled = value;
@@ -3740,9 +3746,9 @@
/// If non-null, sets the [SemanticsConfiguration.isSelected] semantic to the
/// given value.
- bool get selected => _selected;
- bool _selected;
- set selected(bool value) {
+ bool? get selected => _selected;
+ bool? _selected;
+ set selected(bool? value) {
if (selected == value)
return;
_selected = value;
@@ -3751,9 +3757,9 @@
/// If non-null, sets the [SemanticsConfiguration.isButton] semantic to the
/// given value.
- bool get button => _button;
- bool _button;
- set button(bool value) {
+ bool? get button => _button;
+ bool? _button;
+ set button(bool? value) {
if (button == value)
return;
_button = value;
@@ -3762,9 +3768,9 @@
/// If non-null, sets the [SemanticsConfiguration.isLink] semantic to the
/// given value.
- bool get link => _link;
- bool _link;
- set link(bool value) {
+ bool? get link => _link;
+ bool? _link;
+ set link(bool? value) {
if (link == value)
return;
_link = value;
@@ -3773,9 +3779,9 @@
/// If non-null, sets the [SemanticsConfiguration.isHeader] semantic to the
/// given value.
- bool get header => _header;
- bool _header;
- set header(bool value) {
+ bool? get header => _header;
+ bool? _header;
+ set header(bool? value) {
if (header == value)
return;
_header = value;
@@ -3784,9 +3790,9 @@
/// If non-null, sets the [SemanticsConfiguration.isTextField] semantic to the
/// given value.
- bool get textField => _textField;
- bool _textField;
- set textField(bool value) {
+ bool? get textField => _textField;
+ bool? _textField;
+ set textField(bool? value) {
if (textField == value)
return;
_textField = value;
@@ -3795,9 +3801,9 @@
/// If non-null, sets the [SemanticsConfiguration.isReadOnly] semantic to the
/// given value.
- bool get readOnly => _readOnly;
- bool _readOnly;
- set readOnly(bool value) {
+ bool? get readOnly => _readOnly;
+ bool? _readOnly;
+ set readOnly(bool? value) {
if (readOnly == value)
return;
_readOnly = value;
@@ -3806,9 +3812,9 @@
/// If non-null, sets the [SemanticsConfiguration.isFocusable] semantic to the
/// given value.
- bool get focusable => _focusable;
- bool _focusable;
- set focusable(bool value) {
+ bool? get focusable => _focusable;
+ bool? _focusable;
+ set focusable(bool? value) {
if (focusable == value)
return;
_focusable = value;
@@ -3817,9 +3823,9 @@
/// If non-null, sets the [SemanticsConfiguration.isFocused] semantic to the
/// given value.
- bool get focused => _focused;
- bool _focused;
- set focused(bool value) {
+ bool? get focused => _focused;
+ bool? _focused;
+ set focused(bool? value) {
if (focused == value)
return;
_focused = value;
@@ -3828,9 +3834,9 @@
/// If non-null, sets the [SemanticsConfiguration.isInMutuallyExclusiveGroup]
/// semantic to the given value.
- bool get inMutuallyExclusiveGroup => _inMutuallyExclusiveGroup;
- bool _inMutuallyExclusiveGroup;
- set inMutuallyExclusiveGroup(bool value) {
+ bool? get inMutuallyExclusiveGroup => _inMutuallyExclusiveGroup;
+ bool? _inMutuallyExclusiveGroup;
+ set inMutuallyExclusiveGroup(bool? value) {
if (inMutuallyExclusiveGroup == value)
return;
_inMutuallyExclusiveGroup = value;
@@ -3839,9 +3845,9 @@
/// If non-null, sets the [SemanticsConfiguration.isObscured] semantic to the
/// given value.
- bool get obscured => _obscured;
- bool _obscured;
- set obscured(bool value) {
+ bool? get obscured => _obscured;
+ bool? _obscured;
+ set obscured(bool? value) {
if (obscured == value)
return;
_obscured = value;
@@ -3850,9 +3856,9 @@
/// If non-null, sets the [SemanticsNode.isMultiline] semantic to the given
/// value.
- bool get multiline => _multiline;
- bool _multiline;
- set multiline(bool value) {
+ bool? get multiline => _multiline;
+ bool? _multiline;
+ set multiline(bool? value) {
if (multiline == value)
return;
_multiline = value;
@@ -3861,9 +3867,9 @@
/// If non-null, sets the [SemanticsConfiguration.scopesRoute] semantic to the
/// give value.
- bool get scopesRoute => _scopesRoute;
- bool _scopesRoute;
- set scopesRoute(bool value) {
+ bool? get scopesRoute => _scopesRoute;
+ bool? _scopesRoute;
+ set scopesRoute(bool? value) {
if (scopesRoute == value)
return;
_scopesRoute = value;
@@ -3872,9 +3878,9 @@
/// If non-null, sets the [SemanticsConfiguration.namesRoute] semantic to the
/// give value.
- bool get namesRoute => _namesRoute;
- bool _namesRoute;
- set namesRoute(bool value) {
+ bool? get namesRoute => _namesRoute;
+ bool? _namesRoute;
+ set namesRoute(bool? value) {
if (_namesRoute == value)
return;
_namesRoute = value;
@@ -3883,9 +3889,9 @@
/// If non-null, sets the [SemanticsConfiguration.isHidden] semantic to the
/// given value.
- bool get hidden => _hidden;
- bool _hidden;
- set hidden(bool value) {
+ bool? get hidden => _hidden;
+ bool? _hidden;
+ set hidden(bool? value) {
if (hidden == value)
return;
_hidden = value;
@@ -3894,9 +3900,9 @@
/// If non-null, sets the [SemanticsConfiguration.isImage] semantic to the
/// given value.
- bool get image => _image;
- bool _image;
- set image(bool value) {
+ bool? get image => _image;
+ bool? _image;
+ set image(bool? value) {
if (_image == value)
return;
_image = value;
@@ -3904,9 +3910,9 @@
/// If non-null, sets the [SemanticsConfiguration.liveRegion] semantic to
/// the given value.
- bool get liveRegion => _liveRegion;
- bool _liveRegion;
- set liveRegion(bool value) {
+ bool? get liveRegion => _liveRegion;
+ bool? _liveRegion;
+ set liveRegion(bool? value) {
if (_liveRegion == value)
return;
_liveRegion = value;
@@ -3915,9 +3921,9 @@
/// If non-null, sets the [SemanticsNode.maxValueLength] semantic to the given
/// value.
- int get maxValueLength => _maxValueLength;
- int _maxValueLength;
- set maxValueLength(int value) {
+ int? get maxValueLength => _maxValueLength;
+ int? _maxValueLength;
+ set maxValueLength(int? value) {
if (_maxValueLength == value)
return;
_maxValueLength = value;
@@ -3926,9 +3932,9 @@
/// If non-null, sets the [SemanticsNode.currentValueLength] semantic to the
/// given value.
- int get currentValueLength => _currentValueLength;
- int _currentValueLength;
- set currentValueLength(int value) {
+ int? get currentValueLength => _currentValueLength;
+ int? _currentValueLength;
+ set currentValueLength(int? value) {
if (_currentValueLength == value)
return;
_currentValueLength = value;
@@ -3937,9 +3943,9 @@
/// If non-null, sets the [SemanticsConfiguration.isToggled] semantic to the given
/// value.
- bool get toggled => _toggled;
- bool _toggled;
- set toggled(bool value) {
+ bool? get toggled => _toggled;
+ bool? _toggled;
+ set toggled(bool? value) {
if (_toggled == value)
return;
_toggled = value;
@@ -3949,9 +3955,9 @@
/// If non-null, sets the [SemanticsNode.label] semantic to the given value.
///
/// The reading direction is given by [textDirection].
- String get label => _label;
- String _label;
- set label(String value) {
+ String? get label => _label;
+ String? _label;
+ set label(String? value) {
if (_label == value)
return;
_label = value;
@@ -3961,9 +3967,9 @@
/// If non-null, sets the [SemanticsNode.value] semantic to the given value.
///
/// The reading direction is given by [textDirection].
- String get value => _value;
- String _value;
- set value(String value) {
+ String? get value => _value;
+ String? _value;
+ set value(String? value) {
if (_value == value)
return;
_value = value;
@@ -3974,9 +3980,9 @@
/// value.
///
/// The reading direction is given by [textDirection].
- String get increasedValue => _increasedValue;
- String _increasedValue;
- set increasedValue(String value) {
+ String? get increasedValue => _increasedValue;
+ String? _increasedValue;
+ set increasedValue(String? value) {
if (_increasedValue == value)
return;
_increasedValue = value;
@@ -3987,9 +3993,9 @@
/// value.
///
/// The reading direction is given by [textDirection].
- String get decreasedValue => _decreasedValue;
- String _decreasedValue;
- set decreasedValue(String value) {
+ String? get decreasedValue => _decreasedValue;
+ String? _decreasedValue;
+ set decreasedValue(String? value) {
if (_decreasedValue == value)
return;
_decreasedValue = value;
@@ -3999,9 +4005,9 @@
/// If non-null, sets the [SemanticsNode.hint] semantic to the given value.
///
/// The reading direction is given by [textDirection].
- String get hint => _hint;
- String _hint;
- set hint(String value) {
+ String? get hint => _hint;
+ String? _hint;
+ set hint(String? value) {
if (_hint == value)
return;
_hint = value;
@@ -4009,9 +4015,9 @@
}
/// If non-null, sets the [SemanticsConfiguration.hintOverrides] to the given value.
- SemanticsHintOverrides get hintOverrides => _hintOverrides;
- SemanticsHintOverrides _hintOverrides;
- set hintOverrides(SemanticsHintOverrides value) {
+ SemanticsHintOverrides? get hintOverrides => _hintOverrides;
+ SemanticsHintOverrides? _hintOverrides;
+ set hintOverrides(SemanticsHintOverrides? value) {
if (_hintOverrides == value)
return;
_hintOverrides = value;
@@ -4022,9 +4028,9 @@
///
/// This must not be null if [label], [hint], [value], [increasedValue], or
/// [decreasedValue] are not null.
- TextDirection get textDirection => _textDirection;
- TextDirection _textDirection;
- set textDirection(TextDirection value) {
+ TextDirection? get textDirection => _textDirection;
+ TextDirection? _textDirection;
+ set textDirection(TextDirection? value) {
if (textDirection == value)
return;
_textDirection = value;
@@ -4036,9 +4042,9 @@
/// This defines how this node is sorted among the sibling semantics nodes
/// to determine the order in which they are traversed by the accessibility
/// services on the platform (e.g. VoiceOver on iOS and TalkBack on Android).
- SemanticsSortKey get sortKey => _sortKey;
- SemanticsSortKey _sortKey;
- set sortKey(SemanticsSortKey value) {
+ SemanticsSortKey? get sortKey => _sortKey;
+ SemanticsSortKey? _sortKey;
+ set sortKey(SemanticsSortKey? value) {
if (sortKey == value)
return;
_sortKey = value;
@@ -4053,9 +4059,9 @@
///
/// VoiceOver users on iOS and TalkBack users on Android can trigger this
/// action by double-tapping the screen while an element is focused.
- VoidCallback get onTap => _onTap;
- VoidCallback _onTap;
- set onTap(VoidCallback handler) {
+ VoidCallback? get onTap => _onTap;
+ VoidCallback? _onTap;
+ set onTap(VoidCallback? handler) {
if (_onTap == handler)
return;
final bool hadValue = _onTap != null;
@@ -4071,9 +4077,9 @@
/// TalkBack users on Android can trigger this action in the local context
/// menu, and VoiceOver users on iOS can trigger this action with a standard
/// gesture or menu option.
- VoidCallback get onDismiss => _onDismiss;
- VoidCallback _onDismiss;
- set onDismiss(VoidCallback handler) {
+ VoidCallback? get onDismiss => _onDismiss;
+ VoidCallback? _onDismiss;
+ set onDismiss(VoidCallback? handler) {
if (_onDismiss == handler)
return;
final bool hadValue = _onDismiss != null;
@@ -4090,9 +4096,9 @@
/// VoiceOver users on iOS and TalkBack users on Android can trigger this
/// action by double-tapping the screen without lifting the finger after the
/// second tap.
- VoidCallback get onLongPress => _onLongPress;
- VoidCallback _onLongPress;
- set onLongPress(VoidCallback handler) {
+ VoidCallback? get onLongPress => _onLongPress;
+ VoidCallback? _onLongPress;
+ set onLongPress(VoidCallback? handler) {
if (_onLongPress == handler)
return;
final bool hadValue = _onLongPress != null;
@@ -4112,9 +4118,9 @@
/// right and then left in one motion path. On Android, [onScrollUp] and
/// [onScrollLeft] share the same gesture. Therefore, only on of them should
/// be provided.
- VoidCallback get onScrollLeft => _onScrollLeft;
- VoidCallback _onScrollLeft;
- set onScrollLeft(VoidCallback handler) {
+ VoidCallback? get onScrollLeft => _onScrollLeft;
+ VoidCallback? _onScrollLeft;
+ set onScrollLeft(VoidCallback? handler) {
if (_onScrollLeft == handler)
return;
final bool hadValue = _onScrollLeft != null;
@@ -4134,9 +4140,9 @@
/// left and then right in one motion path. On Android, [onScrollDown] and
/// [onScrollRight] share the same gesture. Therefore, only on of them should
/// be provided.
- VoidCallback get onScrollRight => _onScrollRight;
- VoidCallback _onScrollRight;
- set onScrollRight(VoidCallback handler) {
+ VoidCallback? get onScrollRight => _onScrollRight;
+ VoidCallback? _onScrollRight;
+ set onScrollRight(VoidCallback? handler) {
if (_onScrollRight == handler)
return;
final bool hadValue = _onScrollRight != null;
@@ -4156,9 +4162,9 @@
/// right and then left in one motion path. On Android, [onScrollUp] and
/// [onScrollLeft] share the same gesture. Therefore, only on of them should
/// be provided.
- VoidCallback get onScrollUp => _onScrollUp;
- VoidCallback _onScrollUp;
- set onScrollUp(VoidCallback handler) {
+ VoidCallback? get onScrollUp => _onScrollUp;
+ VoidCallback? _onScrollUp;
+ set onScrollUp(VoidCallback? handler) {
if (_onScrollUp == handler)
return;
final bool hadValue = _onScrollUp != null;
@@ -4178,9 +4184,9 @@
/// left and then right in one motion path. On Android, [onScrollDown] and
/// [onScrollRight] share the same gesture. Therefore, only on of them should
/// be provided.
- VoidCallback get onScrollDown => _onScrollDown;
- VoidCallback _onScrollDown;
- set onScrollDown(VoidCallback handler) {
+ VoidCallback? get onScrollDown => _onScrollDown;
+ VoidCallback? _onScrollDown;
+ set onScrollDown(VoidCallback? handler) {
if (_onScrollDown == handler)
return;
final bool hadValue = _onScrollDown != null;
@@ -4197,9 +4203,9 @@
/// VoiceOver users on iOS can trigger this action by swiping up with one
/// finger. TalkBack users on Android can trigger this action by pressing the
/// volume up button.
- VoidCallback get onIncrease => _onIncrease;
- VoidCallback _onIncrease;
- set onIncrease(VoidCallback handler) {
+ VoidCallback? get onIncrease => _onIncrease;
+ VoidCallback? _onIncrease;
+ set onIncrease(VoidCallback? handler) {
if (_onIncrease == handler)
return;
final bool hadValue = _onIncrease != null;
@@ -4216,9 +4222,9 @@
/// VoiceOver users on iOS can trigger this action by swiping down with one
/// finger. TalkBack users on Android can trigger this action by pressing the
/// volume down button.
- VoidCallback get onDecrease => _onDecrease;
- VoidCallback _onDecrease;
- set onDecrease(VoidCallback handler) {
+ VoidCallback? get onDecrease => _onDecrease;
+ VoidCallback? _onDecrease;
+ set onDecrease(VoidCallback? handler) {
if (_onDecrease == handler)
return;
final bool hadValue = _onDecrease != null;
@@ -4233,9 +4239,9 @@
///
/// TalkBack users on Android can trigger this action from the local context
/// menu of a text field, for example.
- VoidCallback get onCopy => _onCopy;
- VoidCallback _onCopy;
- set onCopy(VoidCallback handler) {
+ VoidCallback? get onCopy => _onCopy;
+ VoidCallback? _onCopy;
+ set onCopy(VoidCallback? handler) {
if (_onCopy == handler)
return;
final bool hadValue = _onCopy != null;
@@ -4251,9 +4257,9 @@
///
/// TalkBack users on Android can trigger this action from the local context
/// menu of a text field, for example.
- VoidCallback get onCut => _onCut;
- VoidCallback _onCut;
- set onCut(VoidCallback handler) {
+ VoidCallback? get onCut => _onCut;
+ VoidCallback? _onCut;
+ set onCut(VoidCallback? handler) {
if (_onCut == handler)
return;
final bool hadValue = _onCut != null;
@@ -4268,9 +4274,9 @@
///
/// TalkBack users on Android can trigger this action from the local context
/// menu of a text field, for example.
- VoidCallback get onPaste => _onPaste;
- VoidCallback _onPaste;
- set onPaste(VoidCallback handler) {
+ VoidCallback? get onPaste => _onPaste;
+ VoidCallback? _onPaste;
+ set onPaste(VoidCallback? handler) {
if (_onPaste == handler)
return;
final bool hadValue = _onPaste != null;
@@ -4286,9 +4292,9 @@
///
/// TalkBack users can trigger this by pressing the volume up key while the
/// input focus is in a text field.
- MoveCursorHandler get onMoveCursorForwardByCharacter => _onMoveCursorForwardByCharacter;
- MoveCursorHandler _onMoveCursorForwardByCharacter;
- set onMoveCursorForwardByCharacter(MoveCursorHandler handler) {
+ MoveCursorHandler? get onMoveCursorForwardByCharacter => _onMoveCursorForwardByCharacter;
+ MoveCursorHandler? _onMoveCursorForwardByCharacter;
+ set onMoveCursorForwardByCharacter(MoveCursorHandler? handler) {
if (_onMoveCursorForwardByCharacter == handler)
return;
final bool hadValue = _onMoveCursorForwardByCharacter != null;
@@ -4304,9 +4310,9 @@
///
/// TalkBack users can trigger this by pressing the volume down key while the
/// input focus is in a text field.
- MoveCursorHandler get onMoveCursorBackwardByCharacter => _onMoveCursorBackwardByCharacter;
- MoveCursorHandler _onMoveCursorBackwardByCharacter;
- set onMoveCursorBackwardByCharacter(MoveCursorHandler handler) {
+ MoveCursorHandler? get onMoveCursorBackwardByCharacter => _onMoveCursorBackwardByCharacter;
+ MoveCursorHandler? _onMoveCursorBackwardByCharacter;
+ set onMoveCursorBackwardByCharacter(MoveCursorHandler? handler) {
if (_onMoveCursorBackwardByCharacter == handler)
return;
final bool hadValue = _onMoveCursorBackwardByCharacter != null;
@@ -4322,9 +4328,9 @@
///
/// TalkBack users can trigger this by pressing the volume down key while the
/// input focus is in a text field.
- MoveCursorHandler get onMoveCursorForwardByWord => _onMoveCursorForwardByWord;
- MoveCursorHandler _onMoveCursorForwardByWord;
- set onMoveCursorForwardByWord(MoveCursorHandler handler) {
+ MoveCursorHandler? get onMoveCursorForwardByWord => _onMoveCursorForwardByWord;
+ MoveCursorHandler? _onMoveCursorForwardByWord;
+ set onMoveCursorForwardByWord(MoveCursorHandler? handler) {
if (_onMoveCursorForwardByWord == handler)
return;
final bool hadValue = _onMoveCursorForwardByWord != null;
@@ -4340,9 +4346,9 @@
///
/// TalkBack users can trigger this by pressing the volume down key while the
/// input focus is in a text field.
- MoveCursorHandler get onMoveCursorBackwardByWord => _onMoveCursorBackwardByWord;
- MoveCursorHandler _onMoveCursorBackwardByWord;
- set onMoveCursorBackwardByWord(MoveCursorHandler handler) {
+ MoveCursorHandler? get onMoveCursorBackwardByWord => _onMoveCursorBackwardByWord;
+ MoveCursorHandler? _onMoveCursorBackwardByWord;
+ set onMoveCursorBackwardByWord(MoveCursorHandler? handler) {
if (_onMoveCursorBackwardByWord == handler)
return;
final bool hadValue = _onMoveCursorBackwardByWord != null;
@@ -4358,9 +4364,9 @@
///
/// TalkBack users can trigger this handler by selecting "Move cursor to
/// beginning/end" or "Select all" from the local context menu.
- SetSelectionHandler get onSetSelection => _onSetSelection;
- SetSelectionHandler _onSetSelection;
- set onSetSelection(SetSelectionHandler handler) {
+ SetSelectionHandler? get onSetSelection => _onSetSelection;
+ SetSelectionHandler? _onSetSelection;
+ set onSetSelection(SetSelectionHandler? handler) {
if (_onSetSelection == handler)
return;
final bool hadValue = _onSetSelection != null;
@@ -4386,9 +4392,9 @@
/// * [onDidLoseAccessibilityFocus], which is invoked when the accessibility
/// focus is removed from the node.
/// * [FocusNode], [FocusScope], [FocusManager], which manage the input focus.
- VoidCallback get onDidGainAccessibilityFocus => _onDidGainAccessibilityFocus;
- VoidCallback _onDidGainAccessibilityFocus;
- set onDidGainAccessibilityFocus(VoidCallback handler) {
+ VoidCallback? get onDidGainAccessibilityFocus => _onDidGainAccessibilityFocus;
+ VoidCallback? _onDidGainAccessibilityFocus;
+ set onDidGainAccessibilityFocus(VoidCallback? handler) {
if (_onDidGainAccessibilityFocus == handler)
return;
final bool hadValue = _onDidGainAccessibilityFocus != null;
@@ -4414,9 +4420,9 @@
/// * [onDidGainAccessibilityFocus], which is invoked when the node gains
/// accessibility focus.
/// * [FocusNode], [FocusScope], [FocusManager], which manage the input focus.
- VoidCallback get onDidLoseAccessibilityFocus => _onDidLoseAccessibilityFocus;
- VoidCallback _onDidLoseAccessibilityFocus;
- set onDidLoseAccessibilityFocus(VoidCallback handler) {
+ VoidCallback? get onDidLoseAccessibilityFocus => _onDidLoseAccessibilityFocus;
+ VoidCallback? _onDidLoseAccessibilityFocus;
+ set onDidLoseAccessibilityFocus(VoidCallback? handler) {
if (_onDidLoseAccessibilityFocus == handler)
return;
final bool hadValue = _onDidLoseAccessibilityFocus != null;
@@ -4434,9 +4440,9 @@
/// See also:
///
/// * [CustomSemanticsAction], for an explanation of custom actions.
- Map<CustomSemanticsAction, VoidCallback> get customSemanticsActions => _customSemanticsActions;
- Map<CustomSemanticsAction, VoidCallback> _customSemanticsActions;
- set customSemanticsActions(Map<CustomSemanticsAction, VoidCallback> value) {
+ Map<CustomSemanticsAction, VoidCallback>? get customSemanticsActions => _customSemanticsActions;
+ Map<CustomSemanticsAction, VoidCallback>? _customSemanticsActions;
+ set customSemanticsActions(Map<CustomSemanticsAction, VoidCallback>? value) {
if (_customSemanticsActions == value)
return;
_customSemanticsActions = value;
@@ -4454,7 +4460,8 @@
void describeSemanticsConfiguration(SemanticsConfiguration config) {
super.describeSemanticsConfiguration(config);
config.isSemanticBoundary = container;
- config.explicitChildNodes = explicitChildNodes;
+ if (explicitChildNodes != null)
+ config.explicitChildNodes = explicitChildNodes;
assert((scopesRoute == true && explicitChildNodes == true) || scopesRoute != true,
'explicitChildNodes must be set to true if scopes route is true');
assert(!(toggled == true && checked == true),
@@ -4467,49 +4474,49 @@
if (toggled != null)
config.isToggled = toggled;
if (selected != null)
- config.isSelected = selected;
+ config.isSelected = selected!;
if (button != null)
- config.isButton = button;
+ config.isButton = button!;
if (link != null)
- config.isLink = link;
+ config.isLink = link!;
if (header != null)
- config.isHeader = header;
+ config.isHeader = header!;
if (textField != null)
- config.isTextField = textField;
+ config.isTextField = textField!;
if (readOnly != null)
- config.isReadOnly = readOnly;
+ config.isReadOnly = readOnly!;
if (focusable != null)
- config.isFocusable = focusable;
+ config.isFocusable = focusable!;
if (focused != null)
- config.isFocused = focused;
+ config.isFocused = focused!;
if (inMutuallyExclusiveGroup != null)
- config.isInMutuallyExclusiveGroup = inMutuallyExclusiveGroup;
+ config.isInMutuallyExclusiveGroup = inMutuallyExclusiveGroup!;
if (obscured != null)
- config.isObscured = obscured;
+ config.isObscured = obscured!;
if (multiline != null)
- config.isMultiline = multiline;
+ config.isMultiline = multiline!;
if (hidden != null)
- config.isHidden = hidden;
+ config.isHidden = hidden!;
if (image != null)
- config.isImage = image;
+ config.isImage = image!;
if (label != null)
- config.label = label;
+ config.label = label!;
if (value != null)
- config.value = value;
+ config.value = value!;
if (increasedValue != null)
- config.increasedValue = increasedValue;
+ config.increasedValue = increasedValue!;
if (decreasedValue != null)
- config.decreasedValue = decreasedValue;
+ config.decreasedValue = decreasedValue!;
if (hint != null)
- config.hint = hint;
- if (hintOverrides != null && hintOverrides.isNotEmpty)
+ config.hint = hint!;
+ if (hintOverrides != null && hintOverrides!.isNotEmpty)
config.hintOverrides = hintOverrides;
if (scopesRoute != null)
- config.scopesRoute = scopesRoute;
+ config.scopesRoute = scopesRoute!;
if (namesRoute != null)
- config.namesRoute = namesRoute;
+ config.namesRoute = namesRoute!;
if (liveRegion != null)
- config.liveRegion = liveRegion;
+ config.liveRegion = liveRegion!;
if (maxValueLength != null) {
config.maxValueLength = maxValueLength;
}
@@ -4562,102 +4569,102 @@
if (onDidLoseAccessibilityFocus != null)
config.onDidLoseAccessibilityFocus = _performDidLoseAccessibilityFocus;
if (customSemanticsActions != null)
- config.customSemanticsActions = _customSemanticsActions;
+ config.customSemanticsActions = _customSemanticsActions!;
}
void _performTap() {
if (onTap != null)
- onTap();
+ onTap!();
}
void _performLongPress() {
if (onLongPress != null)
- onLongPress();
+ onLongPress!();
}
void _performDismiss() {
if (onDismiss != null)
- onDismiss();
+ onDismiss!();
}
void _performScrollLeft() {
if (onScrollLeft != null)
- onScrollLeft();
+ onScrollLeft!();
}
void _performScrollRight() {
if (onScrollRight != null)
- onScrollRight();
+ onScrollRight!();
}
void _performScrollUp() {
if (onScrollUp != null)
- onScrollUp();
+ onScrollUp!();
}
void _performScrollDown() {
if (onScrollDown != null)
- onScrollDown();
+ onScrollDown!();
}
void _performIncrease() {
if (onIncrease != null)
- onIncrease();
+ onIncrease!();
}
void _performDecrease() {
if (onDecrease != null)
- onDecrease();
+ onDecrease!();
}
void _performCopy() {
if (onCopy != null)
- onCopy();
+ onCopy!();
}
void _performCut() {
if (onCut != null)
- onCut();
+ onCut!();
}
void _performPaste() {
if (onPaste != null)
- onPaste();
+ onPaste!();
}
void _performMoveCursorForwardByCharacter(bool extendSelection) {
if (onMoveCursorForwardByCharacter != null)
- onMoveCursorForwardByCharacter(extendSelection);
+ onMoveCursorForwardByCharacter!(extendSelection);
}
void _performMoveCursorBackwardByCharacter(bool extendSelection) {
if (onMoveCursorBackwardByCharacter != null)
- onMoveCursorBackwardByCharacter(extendSelection);
+ onMoveCursorBackwardByCharacter!(extendSelection);
}
void _performMoveCursorForwardByWord(bool extendSelection) {
if (onMoveCursorForwardByWord != null)
- onMoveCursorForwardByWord(extendSelection);
+ onMoveCursorForwardByWord!(extendSelection);
}
void _performMoveCursorBackwardByWord(bool extendSelection) {
if (onMoveCursorBackwardByWord != null)
- onMoveCursorBackwardByWord(extendSelection);
+ onMoveCursorBackwardByWord!(extendSelection);
}
void _performSetSelection(TextSelection selection) {
if (onSetSelection != null)
- onSetSelection(selection);
+ onSetSelection!(selection);
}
void _performDidGainAccessibilityFocus() {
if (onDidGainAccessibilityFocus != null)
- onDidGainAccessibilityFocus();
+ onDidGainAccessibilityFocus!();
}
void _performDidLoseAccessibilityFocus() {
if (onDidLoseAccessibilityFocus != null)
- onDidLoseAccessibilityFocus();
+ onDidLoseAccessibilityFocus!();
}
}
@@ -4670,7 +4677,7 @@
/// Create a render object that blocks semantics for nodes below it in paint
/// order.
RenderBlockSemantics({
- RenderBox child,
+ RenderBox? child,
bool blocking = true,
}) : _blocking = blocking,
super(child);
@@ -4709,7 +4716,7 @@
/// and the gesture detector that goes with them.
class RenderMergeSemantics extends RenderProxyBox {
/// Creates a render object that merges the semantics from its descendants.
- RenderMergeSemantics({ RenderBox child }) : super(child);
+ RenderMergeSemantics({ RenderBox? child }) : super(child);
@override
void describeSemanticsConfiguration(SemanticsConfiguration config) {
@@ -4730,7 +4737,7 @@
class RenderExcludeSemantics extends RenderProxyBox {
/// Creates a render object that ignores the semantics of its subtree.
RenderExcludeSemantics({
- RenderBox child,
+ RenderBox? child,
bool excluding = true,
}) : _excluding = excluding,
super(child) {
@@ -4775,8 +4782,8 @@
class RenderIndexedSemantics extends RenderProxyBox {
/// Creates a render object that annotates the child semantics with an index.
RenderIndexedSemantics({
- RenderBox child,
- @required int index,
+ RenderBox? child,
+ required int index,
}) : assert(index != null),
_index = index,
super(child);
@@ -4816,8 +4823,8 @@
///
/// The [link] must not be null.
RenderLeaderLayer({
- @required LayerLink link,
- RenderBox child,
+ required LayerLink link,
+ RenderBox? child,
}) : assert(link != null),
super(child) {
this.link = link;
@@ -4828,8 +4835,8 @@
///
/// This property must not be null. The object must not be associated with
/// another [RenderLeaderLayer] that is also being painted.
- LayerLink get link => _link;
- LayerLink _link;
+ LayerLink get link => _link!;
+ LayerLink? _link;
set link(LayerLink value) {
assert(value != null);
if (_link == value)
@@ -4851,7 +4858,7 @@
..link = link
..offset = offset;
}
- context.pushLayer(layer, super.paint, Offset.zero);
+ context.pushLayer(layer!, super.paint, Offset.zero);
assert(layer != null);
}
@@ -4880,18 +4887,17 @@
///
/// The [link] and [offset] arguments must not be null.
RenderFollowerLayer({
- @required LayerLink link,
+ required LayerLink link,
bool showWhenUnlinked = true,
Offset offset = Offset.zero,
- RenderBox child,
+ RenderBox? child,
}) : assert(link != null),
assert(showWhenUnlinked != null),
assert(offset != null),
- super(child) {
- this.link = link;
- this.showWhenUnlinked = showWhenUnlinked;
- this.offset = offset;
- }
+ _link = link,
+ _showWhenUnlinked = showWhenUnlinked,
+ _offset = offset,
+ super(child);
/// The link object that connects this [RenderFollowerLayer] with a
/// [RenderLeaderLayer] earlier in the paint order.
@@ -4947,7 +4953,7 @@
/// The layer we created when we were last painted.
@override
- FollowerLayer get layer => super.layer as FollowerLayer;
+ FollowerLayer? get layer => super.layer as FollowerLayer?;
/// Return the transform that was used in the last composition phase, if any.
///
@@ -4960,7 +4966,7 @@
}
@override
- bool hitTest(BoxHitTestResult result, { Offset position }) {
+ bool hitTest(BoxHitTestResult result, { required Offset position }) {
// Disables the hit testing if this render object is hidden.
if (link.leader == null && !showWhenUnlinked)
return false;
@@ -4972,12 +4978,12 @@
}
@override
- bool hitTestChildren(BoxHitTestResult result, { Offset position }) {
+ bool hitTestChildren(BoxHitTestResult result, { required Offset position }) {
return result.addWithPaintTransform(
transform: getCurrentTransform(),
position: position,
- hitTest: (BoxHitTestResult result, Offset position) {
- return super.hitTestChildren(result, position: position);
+ hitTest: (BoxHitTestResult result, Offset? position) {
+ return super.hitTestChildren(result, position: position!);
},
);
}
@@ -4993,14 +4999,14 @@
unlinkedOffset: offset,
);
} else {
- layer
+ layer!
..link = link
..showWhenUnlinked = showWhenUnlinked
..linkedOffset = this.offset
..unlinkedOffset = offset;
}
context.pushLayer(
- layer,
+ layer!,
super.paint,
Offset.zero,
childPaintBounds: const Rect.fromLTRB(
@@ -5034,7 +5040,7 @@
///
/// * [Layer.find], for an example of how this value is retrieved.
/// * [AnnotatedRegionLayer], the layer this render object creates.
-class RenderAnnotatedRegion<T> extends RenderProxyBox {
+class RenderAnnotatedRegion<T extends Object> extends RenderProxyBox {
/// Creates a new [RenderAnnotatedRegion] to insert [value] into the
/// layer tree.
@@ -5044,9 +5050,9 @@
///
/// Neither [value] nor [sized] can be null.
RenderAnnotatedRegion({
- @required T value,
- @required bool sized,
- RenderBox child,
+ required T value,
+ required bool sized,
+ RenderBox? child,
}) : assert(value != null),
assert(sized != null),
_value = value,
diff --git a/packages/flutter/lib/src/rendering/proxy_sliver.dart b/packages/flutter/lib/src/rendering/proxy_sliver.dart
index eeb287d..8e9e053 100644
--- a/packages/flutter/lib/src/rendering/proxy_sliver.dart
+++ b/packages/flutter/lib/src/rendering/proxy_sliver.dart
@@ -2,8 +2,6 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-// @dart = 2.8
-
import 'dart:ui' as ui show Color;
import 'package:flutter/animation.dart';
@@ -38,7 +36,7 @@
/// Proxy render slivers aren't created directly because they simply proxy
/// the render sliver protocol to their sliver [child]. Instead, use one of
/// the subclasses.
- RenderProxySliver([RenderSliver child]) {
+ RenderProxySliver([RenderSliver? child]) {
this.child = child;
}
@@ -51,21 +49,21 @@
@override
void performLayout() {
assert(child != null);
- child.layout(constraints, parentUsesSize: true);
- geometry = child.geometry;
+ child!.layout(constraints, parentUsesSize: true);
+ geometry = child!.geometry;
}
@override
void paint(PaintingContext context, Offset offset) {
if (child != null)
- context.paintChild(child, offset);
+ context.paintChild(child!, offset);
}
@override
- bool hitTestChildren(SliverHitTestResult result, {double mainAxisPosition, double crossAxisPosition}) {
+ bool hitTestChildren(SliverHitTestResult result, {required double mainAxisPosition, required double crossAxisPosition}) {
return child != null
- && child.geometry.hitTestExtent > 0
- && child.hitTest(
+ && child!.geometry!.hitTestExtent > 0
+ && child!.hitTest(
result,
mainAxisPosition: mainAxisPosition,
crossAxisPosition: crossAxisPosition,
@@ -104,7 +102,7 @@
RenderSliverOpacity({
double opacity = 1.0,
bool alwaysIncludeSemantics = false,
- RenderSliver sliver,
+ RenderSliver? sliver,
}) : assert(opacity != null && opacity >= 0.0 && opacity <= 1.0),
assert(alwaysIncludeSemantics != null),
_opacity = opacity,
@@ -162,7 +160,7 @@
@override
void paint(PaintingContext context, Offset offset) {
- if (child != null && child.geometry.visible) {
+ if (child != null && child!.geometry!.visible) {
if (_alpha == 0) {
// No need to keep the layer. We'll create a new one if necessary.
layer = null;
@@ -171,7 +169,7 @@
if (_alpha == 255) {
// No need to keep the layer. We'll create a new one if necessary.
layer = null;
- context.paintChild(child, offset);
+ context.paintChild(child!, offset);
return;
}
assert(needsCompositing);
@@ -187,7 +185,7 @@
@override
void visitChildrenForSemantics(RenderObjectVisitor visitor) {
if (child != null && (_alpha != 0 || alwaysIncludeSemantics))
- visitor(child);
+ visitor(child!);
}
@override
@@ -214,9 +212,9 @@
/// The [ignoring] argument must not be null. If [ignoringSemantics] is null,
/// this render object will be ignored for semantics if [ignoring] is true.
RenderSliverIgnorePointer({
- RenderSliver sliver,
+ RenderSliver? sliver,
bool ignoring = true,
- bool ignoringSemantics,
+ bool? ignoringSemantics,
}) : assert(ignoring != null),
_ignoring = ignoring,
_ignoringSemantics = ignoringSemantics {
@@ -234,7 +232,7 @@
if (value == _ignoring)
return;
_ignoring = value;
- if (_ignoringSemantics == null || !_ignoringSemantics)
+ if (_ignoringSemantics == null || !_ignoringSemantics!)
markNeedsSemanticsUpdate();
}
@@ -244,9 +242,9 @@
/// If null, defaults to value of [ignoring].
///
/// See [SemanticsNode] for additional information about the semantics tree.
- bool get ignoringSemantics => _ignoringSemantics;
- bool _ignoringSemantics;
- set ignoringSemantics(bool value) {
+ bool? get ignoringSemantics => _ignoringSemantics;
+ bool? _ignoringSemantics;
+ set ignoringSemantics(bool? value) {
if (value == _ignoringSemantics)
return;
final bool oldEffectiveValue = _effectiveIgnoringSemantics;
@@ -258,7 +256,7 @@
bool get _effectiveIgnoringSemantics => ignoringSemantics ?? ignoring;
@override
- bool hitTest(SliverHitTestResult result, {double mainAxisPosition, double crossAxisPosition}) {
+ bool hitTest(SliverHitTestResult result, {required double mainAxisPosition, required double crossAxisPosition}) {
return !ignoring
&& super.hitTest(
result,
@@ -270,7 +268,7 @@
@override
void visitChildrenForSemantics(RenderObjectVisitor visitor) {
if (child != null && !_effectiveIgnoringSemantics)
- visitor(child);
+ visitor(child!);
}
@override
@@ -288,7 +286,7 @@
/// Creates an offstage render object.
RenderSliverOffstage({
bool offstage = true,
- RenderSliver sliver,
+ RenderSliver? sliver,
}) : assert(offstage != null),
_offstage = offstage {
child = sliver;
@@ -315,9 +313,9 @@
@override
void performLayout() {
assert(child != null);
- child.layout(constraints, parentUsesSize: true);
+ child!.layout(constraints, parentUsesSize: true);
if (!offstage)
- geometry = child.geometry;
+ geometry = child!.geometry;
else
geometry = const SliverGeometry(
scrollExtent: 0.0,
@@ -327,7 +325,7 @@
}
@override
- bool hitTest(SliverHitTestResult result, {double mainAxisPosition, double crossAxisPosition}) {
+ bool hitTest(SliverHitTestResult result, {required double mainAxisPosition, required double crossAxisPosition}) {
return !offstage && super.hitTest(
result,
mainAxisPosition: mainAxisPosition,
@@ -336,11 +334,11 @@
}
@override
- bool hitTestChildren(SliverHitTestResult result, {double mainAxisPosition, double crossAxisPosition}) {
+ bool hitTestChildren(SliverHitTestResult result, {required double mainAxisPosition, required double crossAxisPosition}) {
return !offstage
&& child != null
- && child.geometry.hitTestExtent > 0
- && child.hitTest(
+ && child!.geometry!.hitTestExtent > 0
+ && child!.hitTest(
result,
mainAxisPosition: mainAxisPosition,
crossAxisPosition: crossAxisPosition,
@@ -351,7 +349,7 @@
void paint(PaintingContext context, Offset offset) {
if (offstage)
return;
- context.paintChild(child, offset);
+ context.paintChild(child!, offset);
}
@override
@@ -372,7 +370,7 @@
if (child == null)
return <DiagnosticsNode>[];
return <DiagnosticsNode>[
- child.toDiagnosticsNode(
+ child!.toDiagnosticsNode(
name: 'child',
style: offstage ? DiagnosticsTreeStyle.offstage : DiagnosticsTreeStyle.sparse,
),
@@ -389,9 +387,9 @@
///
/// The [opacity] argument must not be null.
RenderSliverAnimatedOpacity({
- @required Animation<double> opacity,
+ required Animation<double> opacity,
bool alwaysIncludeSemantics = false,
- RenderSliver sliver,
+ RenderSliver? sliver,
}) : assert(opacity != null),
assert(alwaysIncludeSemantics != null) {
this.opacity = opacity;
diff --git a/packages/flutter/lib/src/rendering/rotated_box.dart b/packages/flutter/lib/src/rendering/rotated_box.dart
index ba91d68..e0b155c 100644
--- a/packages/flutter/lib/src/rendering/rotated_box.dart
+++ b/packages/flutter/lib/src/rendering/rotated_box.dart
@@ -2,11 +2,8 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-// @dart = 2.8
-
import 'dart:math' as math;
-import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/painting.dart';
import 'package:vector_math/vector_math_64.dart';
@@ -26,8 +23,8 @@
///
/// The [quarterTurns] argument must not be null.
RenderRotatedBox({
- @required int quarterTurns,
- RenderBox child,
+ required int quarterTurns,
+ RenderBox? child,
}) : assert(quarterTurns != null),
_quarterTurns = quarterTurns {
this.child = child;
@@ -50,75 +47,75 @@
double computeMinIntrinsicWidth(double height) {
if (child == null)
return 0.0;
- return _isVertical ? child.getMinIntrinsicHeight(height) : child.getMinIntrinsicWidth(height);
+ return _isVertical ? child!.getMinIntrinsicHeight(height) : child!.getMinIntrinsicWidth(height);
}
@override
double computeMaxIntrinsicWidth(double height) {
if (child == null)
return 0.0;
- return _isVertical ? child.getMaxIntrinsicHeight(height) : child.getMaxIntrinsicWidth(height);
+ return _isVertical ? child!.getMaxIntrinsicHeight(height) : child!.getMaxIntrinsicWidth(height);
}
@override
double computeMinIntrinsicHeight(double width) {
if (child == null)
return 0.0;
- return _isVertical ? child.getMinIntrinsicWidth(width) : child.getMinIntrinsicHeight(width);
+ return _isVertical ? child!.getMinIntrinsicWidth(width) : child!.getMinIntrinsicHeight(width);
}
@override
double computeMaxIntrinsicHeight(double width) {
if (child == null)
return 0.0;
- return _isVertical ? child.getMaxIntrinsicWidth(width) : child.getMaxIntrinsicHeight(width);
+ return _isVertical ? child!.getMaxIntrinsicWidth(width) : child!.getMaxIntrinsicHeight(width);
}
- Matrix4 _paintTransform;
+ Matrix4? _paintTransform;
@override
void performLayout() {
_paintTransform = null;
if (child != null) {
- child.layout(_isVertical ? constraints.flipped : constraints, parentUsesSize: true);
- size = _isVertical ? Size(child.size.height, child.size.width) : child.size;
+ child!.layout(_isVertical ? constraints.flipped : constraints, parentUsesSize: true);
+ size = _isVertical ? Size(child!.size.height, child!.size.width) : child!.size;
_paintTransform = Matrix4.identity()
..translate(size.width / 2.0, size.height / 2.0)
..rotateZ(_kQuarterTurnsInRadians * (quarterTurns % 4))
- ..translate(-child.size.width / 2.0, -child.size.height / 2.0);
+ ..translate(-child!.size.width / 2.0, -child!.size.height / 2.0);
} else {
performResize();
}
}
@override
- bool hitTestChildren(BoxHitTestResult result, { Offset position }) {
+ bool hitTestChildren(BoxHitTestResult result, { required Offset position }) {
assert(_paintTransform != null || debugNeedsLayout || child == null);
if (child == null || _paintTransform == null)
return false;
return result.addWithPaintTransform(
transform: _paintTransform,
position: position,
- hitTest: (BoxHitTestResult result, Offset position) {
- return child.hitTest(result, position: position);
+ hitTest: (BoxHitTestResult result, Offset? position) {
+ return child!.hitTest(result, position: position!);
},
);
}
void _paintChild(PaintingContext context, Offset offset) {
- context.paintChild(child, offset);
+ context.paintChild(child!, offset);
}
@override
void paint(PaintingContext context, Offset offset) {
if (child != null)
- context.pushTransform(needsCompositing, offset, _paintTransform, _paintChild);
+ context.pushTransform(needsCompositing, offset, _paintTransform!, _paintChild);
}
@override
void applyPaintTransform(RenderBox child, Matrix4 transform) {
if (_paintTransform != null)
- transform.multiply(_paintTransform);
+ transform.multiply(_paintTransform!);
super.applyPaintTransform(child, transform);
}
}
diff --git a/packages/flutter/lib/src/rendering/shifted_box.dart b/packages/flutter/lib/src/rendering/shifted_box.dart
index 4346f37..0727800 100644
--- a/packages/flutter/lib/src/rendering/shifted_box.dart
+++ b/packages/flutter/lib/src/rendering/shifted_box.dart
@@ -2,8 +2,6 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-// @dart = 2.8
-
import 'dart:math' as math;
import 'package:flutter/foundation.dart';
@@ -18,45 +16,45 @@
/// the child's position.
abstract class RenderShiftedBox extends RenderBox with RenderObjectWithChildMixin<RenderBox> {
/// Initializes the [child] property for subclasses.
- RenderShiftedBox(RenderBox child) {
+ RenderShiftedBox(RenderBox? child) {
this.child = child;
}
@override
double computeMinIntrinsicWidth(double height) {
if (child != null)
- return child.getMinIntrinsicWidth(height);
+ return child!.getMinIntrinsicWidth(height);
return 0.0;
}
@override
double computeMaxIntrinsicWidth(double height) {
if (child != null)
- return child.getMaxIntrinsicWidth(height);
+ return child!.getMaxIntrinsicWidth(height);
return 0.0;
}
@override
double computeMinIntrinsicHeight(double width) {
if (child != null)
- return child.getMinIntrinsicHeight(width);
+ return child!.getMinIntrinsicHeight(width);
return 0.0;
}
@override
double computeMaxIntrinsicHeight(double width) {
if (child != null)
- return child.getMaxIntrinsicHeight(width);
+ return child!.getMaxIntrinsicHeight(width);
return 0.0;
}
@override
- double computeDistanceToActualBaseline(TextBaseline baseline) {
- double result;
+ double? computeDistanceToActualBaseline(TextBaseline baseline) {
+ double? result;
if (child != null) {
assert(!debugNeedsLayout);
- result = child.getDistanceToActualBaseline(baseline);
- final BoxParentData childParentData = child.parentData as BoxParentData;
+ result = child!.getDistanceToActualBaseline(baseline);
+ final BoxParentData childParentData = child!.parentData as BoxParentData;
if (result != null)
result += childParentData.offset.dy;
} else {
@@ -68,21 +66,21 @@
@override
void paint(PaintingContext context, Offset offset) {
if (child != null) {
- final BoxParentData childParentData = child.parentData as BoxParentData;
- context.paintChild(child, childParentData.offset + offset);
+ final BoxParentData childParentData = child!.parentData as BoxParentData;
+ context.paintChild(child!, childParentData.offset + offset);
}
}
@override
- bool hitTestChildren(BoxHitTestResult result, { Offset position }) {
+ bool hitTestChildren(BoxHitTestResult result, { required Offset position }) {
if (child != null) {
- final BoxParentData childParentData = child.parentData as BoxParentData;
+ final BoxParentData childParentData = child!.parentData as BoxParentData;
return result.addWithPaintOffset(
offset: childParentData.offset,
position: position,
- hitTest: (BoxHitTestResult result, Offset transformed) {
+ hitTest: (BoxHitTestResult result, Offset? transformed) {
assert(transformed == position - childParentData.offset);
- return child.hitTest(result, position: transformed);
+ return child!.hitTest(result, position: transformed!);
},
);
}
@@ -102,22 +100,22 @@
///
/// The [padding] argument must not be null and must have non-negative insets.
RenderPadding({
- @required EdgeInsetsGeometry padding,
- TextDirection textDirection,
- RenderBox child,
+ required EdgeInsetsGeometry padding,
+ TextDirection? textDirection,
+ RenderBox? child,
}) : assert(padding != null),
assert(padding.isNonNegative),
_textDirection = textDirection,
_padding = padding,
super(child);
- EdgeInsets _resolvedPadding;
+ EdgeInsets? _resolvedPadding;
void _resolve() {
if (_resolvedPadding != null)
return;
_resolvedPadding = padding.resolve(textDirection);
- assert(_resolvedPadding.isNonNegative);
+ assert(_resolvedPadding!.isNonNegative);
}
void _markNeedResolution() {
@@ -144,9 +142,9 @@
///
/// This may be changed to null, but only after the [padding] has been changed
/// to a value that does not depend on the direction.
- TextDirection get textDirection => _textDirection;
- TextDirection _textDirection;
- set textDirection(TextDirection value) {
+ TextDirection? get textDirection => _textDirection;
+ TextDirection? _textDirection;
+ set textDirection(TextDirection? value) {
if (_textDirection == value)
return;
_textDirection = value;
@@ -156,40 +154,40 @@
@override
double computeMinIntrinsicWidth(double height) {
_resolve();
- final double totalHorizontalPadding = _resolvedPadding.left + _resolvedPadding.right;
- final double totalVerticalPadding = _resolvedPadding.top + _resolvedPadding.bottom;
+ final double totalHorizontalPadding = _resolvedPadding!.left + _resolvedPadding!.right;
+ final double totalVerticalPadding = _resolvedPadding!.top + _resolvedPadding!.bottom;
if (child != null) // next line relies on double.infinity absorption
- return child.getMinIntrinsicWidth(math.max(0.0, height - totalVerticalPadding)) + totalHorizontalPadding;
+ return child!.getMinIntrinsicWidth(math.max(0.0, height - totalVerticalPadding)) + totalHorizontalPadding;
return totalHorizontalPadding;
}
@override
double computeMaxIntrinsicWidth(double height) {
_resolve();
- final double totalHorizontalPadding = _resolvedPadding.left + _resolvedPadding.right;
- final double totalVerticalPadding = _resolvedPadding.top + _resolvedPadding.bottom;
+ final double totalHorizontalPadding = _resolvedPadding!.left + _resolvedPadding!.right;
+ final double totalVerticalPadding = _resolvedPadding!.top + _resolvedPadding!.bottom;
if (child != null) // next line relies on double.infinity absorption
- return child.getMaxIntrinsicWidth(math.max(0.0, height - totalVerticalPadding)) + totalHorizontalPadding;
+ return child!.getMaxIntrinsicWidth(math.max(0.0, height - totalVerticalPadding)) + totalHorizontalPadding;
return totalHorizontalPadding;
}
@override
double computeMinIntrinsicHeight(double width) {
_resolve();
- final double totalHorizontalPadding = _resolvedPadding.left + _resolvedPadding.right;
- final double totalVerticalPadding = _resolvedPadding.top + _resolvedPadding.bottom;
+ final double totalHorizontalPadding = _resolvedPadding!.left + _resolvedPadding!.right;
+ final double totalVerticalPadding = _resolvedPadding!.top + _resolvedPadding!.bottom;
if (child != null) // next line relies on double.infinity absorption
- return child.getMinIntrinsicHeight(math.max(0.0, width - totalHorizontalPadding)) + totalVerticalPadding;
+ return child!.getMinIntrinsicHeight(math.max(0.0, width - totalHorizontalPadding)) + totalVerticalPadding;
return totalVerticalPadding;
}
@override
double computeMaxIntrinsicHeight(double width) {
_resolve();
- final double totalHorizontalPadding = _resolvedPadding.left + _resolvedPadding.right;
- final double totalVerticalPadding = _resolvedPadding.top + _resolvedPadding.bottom;
+ final double totalHorizontalPadding = _resolvedPadding!.left + _resolvedPadding!.right;
+ final double totalVerticalPadding = _resolvedPadding!.top + _resolvedPadding!.bottom;
if (child != null) // next line relies on double.infinity absorption
- return child.getMaxIntrinsicHeight(math.max(0.0, width - totalHorizontalPadding)) + totalVerticalPadding;
+ return child!.getMaxIntrinsicHeight(math.max(0.0, width - totalHorizontalPadding)) + totalVerticalPadding;
return totalVerticalPadding;
}
@@ -200,18 +198,18 @@
assert(_resolvedPadding != null);
if (child == null) {
size = constraints.constrain(Size(
- _resolvedPadding.left + _resolvedPadding.right,
- _resolvedPadding.top + _resolvedPadding.bottom,
+ _resolvedPadding!.left + _resolvedPadding!.right,
+ _resolvedPadding!.top + _resolvedPadding!.bottom,
));
return;
}
- final BoxConstraints innerConstraints = constraints.deflate(_resolvedPadding);
- child.layout(innerConstraints, parentUsesSize: true);
- final BoxParentData childParentData = child.parentData as BoxParentData;
- childParentData.offset = Offset(_resolvedPadding.left, _resolvedPadding.top);
+ final BoxConstraints innerConstraints = constraints.deflate(_resolvedPadding!);
+ child!.layout(innerConstraints, parentUsesSize: true);
+ final BoxParentData childParentData = child!.parentData as BoxParentData;
+ childParentData.offset = Offset(_resolvedPadding!.left, _resolvedPadding!.top);
size = constraints.constrain(Size(
- _resolvedPadding.left + child.size.width + _resolvedPadding.right,
- _resolvedPadding.top + child.size.height + _resolvedPadding.bottom,
+ _resolvedPadding!.left + child!.size.width + _resolvedPadding!.right,
+ _resolvedPadding!.top + child!.size.height + _resolvedPadding!.bottom,
));
}
@@ -220,7 +218,7 @@
super.debugPaintSize(context, offset);
assert(() {
final Rect outerRect = offset & size;
- debugPaintPadding(context.canvas, outerRect, child != null ? _resolvedPadding.deflateRect(outerRect) : null);
+ debugPaintPadding(context.canvas, outerRect, child != null ? _resolvedPadding!.deflateRect(outerRect) : null);
return true;
}());
}
@@ -244,8 +242,8 @@
/// direction-sensitive.
RenderAligningShiftedBox({
AlignmentGeometry alignment = Alignment.center,
- @required TextDirection textDirection,
- RenderBox child,
+ required TextDirection? textDirection,
+ RenderBox? child,
}) : assert(alignment != null),
_alignment = alignment,
_textDirection = textDirection,
@@ -254,10 +252,10 @@
/// A constructor to be used only when the extending class also has a mixin.
// TODO(gspencer): Remove this constructor once https://github.com/dart-lang/sdk/issues/31543 is fixed.
@protected
- RenderAligningShiftedBox.mixin(AlignmentGeometry alignment, TextDirection textDirection, RenderBox child)
+ RenderAligningShiftedBox.mixin(AlignmentGeometry alignment, TextDirection? textDirection, RenderBox? child)
: this(alignment: alignment, textDirection: textDirection, child: child);
- Alignment _resolvedAlignment;
+ Alignment? _resolvedAlignment;
void _resolve() {
if (_resolvedAlignment != null)
@@ -299,9 +297,9 @@
///
/// This may be changed to null, but only after [alignment] has been changed
/// to a value that does not depend on the direction.
- TextDirection get textDirection => _textDirection;
- TextDirection _textDirection;
- set textDirection(TextDirection value) {
+ TextDirection? get textDirection => _textDirection;
+ TextDirection? _textDirection;
+ set textDirection(TextDirection? value) {
if (_textDirection == value)
return;
_textDirection = value;
@@ -320,12 +318,12 @@
void alignChild() {
_resolve();
assert(child != null);
- assert(!child.debugNeedsLayout);
- assert(child.hasSize);
+ assert(!child!.debugNeedsLayout);
+ assert(child!.hasSize);
assert(hasSize);
assert(_resolvedAlignment != null);
- final BoxParentData childParentData = child.parentData as BoxParentData;
- childParentData.offset = _resolvedAlignment.alongOffset(size - child.size as Offset);
+ final BoxParentData childParentData = child!.parentData as BoxParentData;
+ childParentData.offset = _resolvedAlignment!.alongOffset(size - child!.size as Offset);
}
@override
@@ -349,11 +347,11 @@
class RenderPositionedBox extends RenderAligningShiftedBox {
/// Creates a render object that positions its child.
RenderPositionedBox({
- RenderBox child,
- double widthFactor,
- double heightFactor,
+ RenderBox? child,
+ double? widthFactor,
+ double? heightFactor,
AlignmentGeometry alignment = Alignment.center,
- TextDirection textDirection,
+ TextDirection? textDirection,
}) : assert(widthFactor == null || widthFactor >= 0.0),
assert(heightFactor == null || heightFactor >= 0.0),
_widthFactor = widthFactor,
@@ -363,9 +361,9 @@
/// If non-null, sets its width to the child's width multiplied by this factor.
///
/// Can be both greater and less than 1.0 but must be positive.
- double get widthFactor => _widthFactor;
- double _widthFactor;
- set widthFactor(double value) {
+ double? get widthFactor => _widthFactor;
+ double? _widthFactor;
+ set widthFactor(double? value) {
assert(value == null || value >= 0.0);
if (_widthFactor == value)
return;
@@ -376,9 +374,9 @@
/// If non-null, sets its height to the child's height multiplied by this factor.
///
/// Can be both greater and less than 1.0 but must be positive.
- double get heightFactor => _heightFactor;
- double _heightFactor;
- set heightFactor(double value) {
+ double? get heightFactor => _heightFactor;
+ double? _heightFactor;
+ set heightFactor(double? value) {
assert(value == null || value >= 0.0);
if (_heightFactor == value)
return;
@@ -393,9 +391,9 @@
final bool shrinkWrapHeight = _heightFactor != null || constraints.maxHeight == double.infinity;
if (child != null) {
- child.layout(constraints.loosen(), parentUsesSize: true);
- size = constraints.constrain(Size(shrinkWrapWidth ? child.size.width * (_widthFactor ?? 1.0) : double.infinity,
- shrinkWrapHeight ? child.size.height * (_heightFactor ?? 1.0) : double.infinity));
+ child!.layout(constraints.loosen(), parentUsesSize: true);
+ size = constraints.constrain(Size(shrinkWrapWidth ? child!.size.width * (_widthFactor ?? 1.0) : double.infinity,
+ shrinkWrapHeight ? child!.size.height * (_heightFactor ?? 1.0) : double.infinity));
alignChild();
} else {
size = constraints.constrain(Size(shrinkWrapWidth ? 0.0 : double.infinity,
@@ -408,14 +406,14 @@
super.debugPaintSize(context, offset);
assert(() {
Paint paint;
- if (child != null && !child.size.isEmpty) {
+ if (child != null && !child!.size.isEmpty) {
Path path;
paint = Paint()
..style = PaintingStyle.stroke
..strokeWidth = 1.0
..color = const Color(0xFFFFFF00);
path = Path();
- final BoxParentData childParentData = child.parentData as BoxParentData;
+ final BoxParentData childParentData = child!.parentData as BoxParentData;
if (childParentData.offset.dy > 0.0) {
// vertical alignment arrows
final double headSize = math.min(childParentData.offset.dy * 0.2, 10.0);
@@ -502,13 +500,13 @@
class RenderConstrainedOverflowBox extends RenderAligningShiftedBox {
/// Creates a render object that lets its child overflow itself.
RenderConstrainedOverflowBox({
- RenderBox child,
- double minWidth,
- double maxWidth,
- double minHeight,
- double maxHeight,
+ RenderBox? child,
+ double? minWidth,
+ double? maxWidth,
+ double? minHeight,
+ double? maxHeight,
AlignmentGeometry alignment = Alignment.center,
- TextDirection textDirection,
+ TextDirection? textDirection,
}) : _minWidth = minWidth,
_maxWidth = maxWidth,
_minHeight = minHeight,
@@ -517,9 +515,9 @@
/// The minimum width constraint to give the child. Set this to null (the
/// default) to use the constraint from the parent instead.
- double get minWidth => _minWidth;
- double _minWidth;
- set minWidth(double value) {
+ double? get minWidth => _minWidth;
+ double? _minWidth;
+ set minWidth(double? value) {
if (_minWidth == value)
return;
_minWidth = value;
@@ -528,9 +526,9 @@
/// The maximum width constraint to give the child. Set this to null (the
/// default) to use the constraint from the parent instead.
- double get maxWidth => _maxWidth;
- double _maxWidth;
- set maxWidth(double value) {
+ double? get maxWidth => _maxWidth;
+ double? _maxWidth;
+ set maxWidth(double? value) {
if (_maxWidth == value)
return;
_maxWidth = value;
@@ -539,9 +537,9 @@
/// The minimum height constraint to give the child. Set this to null (the
/// default) to use the constraint from the parent instead.
- double get minHeight => _minHeight;
- double _minHeight;
- set minHeight(double value) {
+ double? get minHeight => _minHeight;
+ double? _minHeight;
+ set minHeight(double? value) {
if (_minHeight == value)
return;
_minHeight = value;
@@ -550,9 +548,9 @@
/// The maximum height constraint to give the child. Set this to null (the
/// default) to use the constraint from the parent instead.
- double get maxHeight => _maxHeight;
- double _maxHeight;
- set maxHeight(double value) {
+ double? get maxHeight => _maxHeight;
+ double? _maxHeight;
+ set maxHeight(double? value) {
if (_maxHeight == value)
return;
_maxHeight = value;
@@ -579,7 +577,7 @@
@override
void performLayout() {
if (child != null) {
- child.layout(_getInnerConstraints(constraints), parentUsesSize: true);
+ child?.layout(_getInnerConstraints(constraints), parentUsesSize: true);
alignChild();
}
}
@@ -624,10 +622,10 @@
///
/// The [alignment] must not be null.
RenderUnconstrainedBox({
- @required AlignmentGeometry alignment,
- @required TextDirection textDirection,
- Axis constrainedAxis,
- RenderBox child,
+ required AlignmentGeometry alignment,
+ required TextDirection? textDirection,
+ Axis? constrainedAxis,
+ RenderBox? child,
Clip clipBehavior = Clip.none,
}) : assert(alignment != null),
assert(clipBehavior != null),
@@ -641,9 +639,9 @@
/// constraints. If set to [Axis.vertical], then vertical constraints will
/// be retained, and if set to [Axis.horizontal], then horizontal constraints
/// will be retained.
- Axis get constrainedAxis => _constrainedAxis;
- Axis _constrainedAxis;
- set constrainedAxis(Axis value) {
+ Axis? get constrainedAxis => _constrainedAxis;
+ Axis? _constrainedAxis;
+ set constrainedAxis(Axis? value) {
if (_constrainedAxis == value)
return;
_constrainedAxis = value;
@@ -676,7 +674,7 @@
// constrainedAxis is non-null, keep any constraints on that axis.
BoxConstraints childConstraints;
if (constrainedAxis != null) {
- switch (constrainedAxis) {
+ switch (constrainedAxis!) {
case Axis.horizontal:
childConstraints = BoxConstraints(maxWidth: constraints.maxWidth, minWidth: constraints.minWidth);
break;
@@ -687,12 +685,12 @@
} else {
childConstraints = const BoxConstraints();
}
- child.layout(childConstraints, parentUsesSize: true);
- size = constraints.constrain(child.size);
+ child!.layout(childConstraints, parentUsesSize: true);
+ size = constraints.constrain(child!.size);
alignChild();
- final BoxParentData childParentData = child.parentData as BoxParentData;
+ final BoxParentData childParentData = child!.parentData as BoxParentData;
_overflowContainerRect = Offset.zero & size;
- _overflowChildRect = childParentData.offset & child.size;
+ _overflowChildRect = childParentData.offset & child!.size;
} else {
size = constraints.smallest;
_overflowContainerRect = Rect.zero;
@@ -728,7 +726,7 @@
}
@override
- Rect describeApproximatePaintClip(RenderObject child) {
+ Rect? describeApproximatePaintClip(RenderObject child) {
return _isOverflowing ? Offset.zero & size : null;
}
@@ -763,10 +761,10 @@
/// The [textDirection] argument must not be null if the [alignment] is
/// direction-sensitive.
RenderSizedOverflowBox({
- RenderBox child,
- @required Size requestedSize,
+ RenderBox? child,
+ required Size requestedSize,
AlignmentGeometry alignment = Alignment.center,
- TextDirection textDirection,
+ TextDirection? textDirection,
}) : assert(requestedSize != null),
_requestedSize = requestedSize,
super(child: child, alignment: alignment, textDirection: textDirection);
@@ -803,9 +801,9 @@
}
@override
- double computeDistanceToActualBaseline(TextBaseline baseline) {
+ double? computeDistanceToActualBaseline(TextBaseline baseline) {
if (child != null)
- return child.getDistanceToActualBaseline(baseline);
+ return child!.getDistanceToActualBaseline(baseline);
return super.computeDistanceToActualBaseline(baseline);
}
@@ -813,7 +811,7 @@
void performLayout() {
size = constraints.constrain(_requestedSize);
if (child != null) {
- child.layout(constraints, parentUsesSize: true);
+ child!.layout(constraints, parentUsesSize: true);
alignChild();
}
}
@@ -841,16 +839,16 @@
/// The [textDirection] must be non-null if the [alignment] is
/// direction-sensitive.
RenderFractionallySizedOverflowBox({
- RenderBox child,
- double widthFactor,
- double heightFactor,
+ RenderBox? child,
+ double? widthFactor,
+ double? heightFactor,
AlignmentGeometry alignment = Alignment.center,
- TextDirection textDirection,
+ TextDirection? textDirection,
}) : _widthFactor = widthFactor,
_heightFactor = heightFactor,
super(child: child, alignment: alignment, textDirection: textDirection) {
- assert(_widthFactor == null || _widthFactor >= 0.0);
- assert(_heightFactor == null || _heightFactor >= 0.0);
+ assert(_widthFactor == null || _widthFactor! >= 0.0);
+ assert(_heightFactor == null || _heightFactor! >= 0.0);
}
/// If non-null, the factor of the incoming width to use.
@@ -858,9 +856,9 @@
/// If non-null, the child is given a tight width constraint that is the max
/// incoming width constraint multiplied by this factor. If null, the child is
/// given the incoming width constraints.
- double get widthFactor => _widthFactor;
- double _widthFactor;
- set widthFactor(double value) {
+ double? get widthFactor => _widthFactor;
+ double? _widthFactor;
+ set widthFactor(double? value) {
assert(value == null || value >= 0.0);
if (_widthFactor == value)
return;
@@ -873,9 +871,9 @@
/// If non-null, the child is given a tight height constraint that is the max
/// incoming width constraint multiplied by this factor. If null, the child is
/// given the incoming width constraints.
- double get heightFactor => _heightFactor;
- double _heightFactor;
- set heightFactor(double value) {
+ double? get heightFactor => _heightFactor;
+ double? _heightFactor;
+ set heightFactor(double? value) {
assert(value == null || value >= 0.0);
if (_heightFactor == value)
return;
@@ -887,14 +885,14 @@
double minWidth = constraints.minWidth;
double maxWidth = constraints.maxWidth;
if (_widthFactor != null) {
- final double width = maxWidth * _widthFactor;
+ final double width = maxWidth * _widthFactor!;
minWidth = width;
maxWidth = width;
}
double minHeight = constraints.minHeight;
double maxHeight = constraints.maxHeight;
if (_heightFactor != null) {
- final double height = maxHeight * _heightFactor;
+ final double height = maxHeight * _heightFactor!;
minHeight = height;
maxHeight = height;
}
@@ -912,7 +910,7 @@
if (child == null) {
result = super.computeMinIntrinsicWidth(height);
} else { // the following line relies on double.infinity absorption
- result = child.getMinIntrinsicWidth(height * (_heightFactor ?? 1.0));
+ result = child!.getMinIntrinsicWidth(height * (_heightFactor ?? 1.0));
}
assert(result.isFinite);
return result / (_widthFactor ?? 1.0);
@@ -924,7 +922,7 @@
if (child == null) {
result = super.computeMaxIntrinsicWidth(height);
} else { // the following line relies on double.infinity absorption
- result = child.getMaxIntrinsicWidth(height * (_heightFactor ?? 1.0));
+ result = child!.getMaxIntrinsicWidth(height * (_heightFactor ?? 1.0));
}
assert(result.isFinite);
return result / (_widthFactor ?? 1.0);
@@ -936,7 +934,7 @@
if (child == null) {
result = super.computeMinIntrinsicHeight(width);
} else { // the following line relies on double.infinity absorption
- result = child.getMinIntrinsicHeight(width * (_widthFactor ?? 1.0));
+ result = child!.getMinIntrinsicHeight(width * (_widthFactor ?? 1.0));
}
assert(result.isFinite);
return result / (_heightFactor ?? 1.0);
@@ -948,7 +946,7 @@
if (child == null) {
result = super.computeMaxIntrinsicHeight(width);
} else { // the following line relies on double.infinity absorption
- result = child.getMaxIntrinsicHeight(width * (_widthFactor ?? 1.0));
+ result = child!.getMaxIntrinsicHeight(width * (_widthFactor ?? 1.0));
}
assert(result.isFinite);
return result / (_heightFactor ?? 1.0);
@@ -957,8 +955,8 @@
@override
void performLayout() {
if (child != null) {
- child.layout(_getInnerConstraints(constraints), parentUsesSize: true);
- size = constraints.constrain(child.size);
+ child!.layout(_getInnerConstraints(constraints), parentUsesSize: true);
+ size = constraints.constrain(child!.size);
alignChild();
} else {
size = constraints.constrain(_getInnerConstraints(constraints).constrain(Size.zero));
@@ -1003,9 +1001,9 @@
/// Creates a layout delegate.
///
/// The layout will update whenever [relayout] notifies its listeners.
- const SingleChildLayoutDelegate({ Listenable relayout }) : _relayout = relayout;
+ const SingleChildLayoutDelegate({ Listenable? relayout }) : _relayout = relayout;
- final Listenable _relayout;
+ final Listenable? _relayout;
/// The size of this object given the incoming constraints.
///
@@ -1065,8 +1063,8 @@
///
/// The [delegate] argument must not be null.
RenderCustomSingleChildLayoutBox({
- RenderBox child,
- @required SingleChildLayoutDelegate delegate,
+ RenderBox? child,
+ required SingleChildLayoutDelegate delegate,
}) : assert(delegate != null),
_delegate = delegate,
super(child);
@@ -1083,20 +1081,20 @@
markNeedsLayout();
_delegate = newDelegate;
if (attached) {
- oldDelegate?._relayout?.removeListener(markNeedsLayout);
- newDelegate?._relayout?.addListener(markNeedsLayout);
+ oldDelegate._relayout?.removeListener(markNeedsLayout);
+ newDelegate._relayout?.addListener(markNeedsLayout);
}
}
@override
void attach(PipelineOwner owner) {
super.attach(owner);
- _delegate?._relayout?.addListener(markNeedsLayout);
+ _delegate._relayout?.addListener(markNeedsLayout);
}
@override
void detach() {
- _delegate?._relayout?.removeListener(markNeedsLayout);
+ _delegate._relayout?.removeListener(markNeedsLayout);
super.detach();
}
@@ -1146,9 +1144,9 @@
if (child != null) {
final BoxConstraints childConstraints = delegate.getConstraintsForChild(constraints);
assert(childConstraints.debugAssertIsValid(isAppliedConstraint: true));
- child.layout(childConstraints, parentUsesSize: !childConstraints.isTight);
- final BoxParentData childParentData = child.parentData as BoxParentData;
- childParentData.offset = delegate.getPositionForChild(size, childConstraints.isTight ? childConstraints.smallest : child.size);
+ child!.layout(childConstraints, parentUsesSize: !childConstraints.isTight);
+ final BoxParentData childParentData = child!.parentData as BoxParentData;
+ childParentData.offset = delegate.getPositionForChild(size, childConstraints.isTight ? childConstraints.smallest : child!.size);
}
}
}
@@ -1174,9 +1172,9 @@
///
/// The [baseline] and [baselineType] arguments must not be null.
RenderBaseline({
- RenderBox child,
- @required double baseline,
- @required TextBaseline baselineType,
+ RenderBox? child,
+ required double baseline,
+ required TextBaseline baselineType,
}) : assert(baseline != null),
assert(baselineType != null),
_baseline = baseline,
@@ -1210,13 +1208,13 @@
void performLayout() {
if (child != null) {
final BoxConstraints constraints = this.constraints;
- child.layout(constraints.loosen(), parentUsesSize: true);
- final double childBaseline = child.getDistanceToBaseline(baselineType);
+ child!.layout(constraints.loosen(), parentUsesSize: true);
+ final double childBaseline = child!.getDistanceToBaseline(baselineType)!;
final double actualBaseline = baseline;
final double top = actualBaseline - childBaseline;
- final BoxParentData childParentData = child.parentData as BoxParentData;
+ final BoxParentData childParentData = child!.parentData as BoxParentData;
childParentData.offset = Offset(0.0, top);
- final Size childSize = child.size;
+ final Size childSize = child!.size;
size = constraints.constrain(Size(childSize.width, top + childSize.height));
} else {
performResize();
diff --git a/packages/flutter/lib/src/rendering/sliver.dart b/packages/flutter/lib/src/rendering/sliver.dart
index 92cadd1..22315a9 100644
--- a/packages/flutter/lib/src/rendering/sliver.dart
+++ b/packages/flutter/lib/src/rendering/sliver.dart
@@ -2,8 +2,6 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-// @dart = 2.8
-
import 'dart:math' as math;
import 'package:flutter/foundation.dart';
@@ -61,7 +59,6 @@
case GrowthDirection.reverse:
return flipAxisDirection(axisDirection);
}
- return null;
}
/// Flips the [ScrollDirection] if the [GrowthDirection] is [GrowthDirection.reverse].
@@ -82,7 +79,6 @@
case GrowthDirection.reverse:
return flipScrollDirection(scrollDirection);
}
- return null;
}
/// Immutable layout constraints for [RenderSliver] layout.
@@ -97,18 +93,18 @@
///
/// All of the argument must not be null.
const SliverConstraints({
- @required this.axisDirection,
- @required this.growthDirection,
- @required this.userScrollDirection,
- @required this.scrollOffset,
- @required this.precedingScrollExtent,
- @required this.overlap,
- @required this.remainingPaintExtent,
- @required this.crossAxisExtent,
- @required this.crossAxisDirection,
- @required this.viewportMainAxisExtent,
- @required this.remainingCacheExtent,
- @required this.cacheOrigin,
+ required this.axisDirection,
+ required this.growthDirection,
+ required this.userScrollDirection,
+ required this.scrollOffset,
+ required this.precedingScrollExtent,
+ required this.overlap,
+ required this.remainingPaintExtent,
+ required this.crossAxisExtent,
+ required this.crossAxisDirection,
+ required this.viewportMainAxisExtent,
+ required this.remainingCacheExtent,
+ required this.cacheOrigin,
}) : assert(axisDirection != null),
assert(growthDirection != null),
assert(userScrollDirection != null),
@@ -125,18 +121,18 @@
/// Creates a copy of this object but with the given fields replaced with the
/// new values.
SliverConstraints copyWith({
- AxisDirection axisDirection,
- GrowthDirection growthDirection,
- ScrollDirection userScrollDirection,
- double scrollOffset,
- double precedingScrollExtent,
- double overlap,
- double remainingPaintExtent,
- double crossAxisExtent,
- AxisDirection crossAxisDirection,
- double viewportMainAxisExtent,
- double remainingCacheExtent,
- double cacheOrigin,
+ AxisDirection? axisDirection,
+ GrowthDirection? growthDirection,
+ ScrollDirection? userScrollDirection,
+ double? scrollOffset,
+ double? precedingScrollExtent,
+ double? overlap,
+ double? remainingPaintExtent,
+ double? crossAxisExtent,
+ AxisDirection? crossAxisDirection,
+ double? viewportMainAxisExtent,
+ double? remainingCacheExtent,
+ double? cacheOrigin,
}) {
return SliverConstraints(
axisDirection: axisDirection ?? this.axisDirection,
@@ -360,9 +356,7 @@
case GrowthDirection.reverse:
return GrowthDirection.forward;
}
- return null;
}
- return null;
}
@override
@@ -388,7 +382,7 @@
BoxConstraints asBoxConstraints({
double minExtent = 0.0,
double maxExtent = double.infinity,
- double crossAxisExtent,
+ double? crossAxisExtent,
}) {
crossAxisExtent ??= this.crossAxisExtent;
switch (axis) {
@@ -407,13 +401,12 @@
maxHeight: maxExtent,
);
}
- return null;
}
@override
bool debugAssertIsValid({
bool isAppliedConstraint = false,
- InformationCollector informationCollector,
+ InformationCollector? informationCollector,
}) {
assert(() {
bool hasErrors = false;
@@ -540,14 +533,14 @@
this.scrollExtent = 0.0,
this.paintExtent = 0.0,
this.paintOrigin = 0.0,
- double layoutExtent,
+ double? layoutExtent,
this.maxPaintExtent = 0.0,
this.maxScrollObstructionExtent = 0.0,
- double hitTestExtent,
- bool visible,
+ double? hitTestExtent,
+ bool? visible,
this.hasVisualOverflow = false,
this.scrollOffsetCorrection,
- double cacheExtent,
+ double? cacheExtent,
}) : assert(scrollExtent != null),
assert(paintExtent != null),
assert(paintOrigin != null),
@@ -692,7 +685,7 @@
/// If the parent is also a [RenderSliver], it must propagate this value
/// in its own [RenderSliver.geometry] property until a viewport which adjusts
/// its offset based on this value.
- final double scrollOffsetCorrection;
+ final double? scrollOffsetCorrection;
/// How many pixels the sliver has consumed in the
/// [SliverConstraints.remainingCacheExtent].
@@ -711,10 +704,10 @@
///
/// Does nothing if asserts are disabled. Always returns true.
bool debugAssertIsValid({
- InformationCollector informationCollector,
+ InformationCollector? informationCollector,
}) {
assert(() {
- void verify(bool check, String summary, {List<DiagnosticsNode> details}) {
+ void verify(bool check, String summary, {List<DiagnosticsNode>? details}) {
if (check)
return;
throw FlutterError.fromParts(<DiagnosticsNode>[
@@ -797,7 +790,7 @@
///
/// * [RenderSliver.hitTest], which documents more details around hit testing
/// [RenderSliver]s.
-typedef SliverHitTest = bool Function(SliverHitTestResult result, { @required double mainAxisPosition, @required double crossAxisPosition });
+typedef SliverHitTest = bool Function(SliverHitTestResult result, { required double mainAxisPosition, required double crossAxisPosition });
/// The result of performing a hit test on [RenderSliver]s.
///
@@ -848,12 +841,12 @@
///
/// The function returns the return value of `hitTest`.
bool addWithAxisOffset({
- @required Offset paintOffset,
- @required double mainAxisOffset,
- @required double crossAxisOffset,
- @required double mainAxisPosition,
- @required double crossAxisPosition,
- @required SliverHitTest hitTest,
+ required Offset? paintOffset,
+ required double mainAxisOffset,
+ required double crossAxisOffset,
+ required double mainAxisPosition,
+ required double crossAxisPosition,
+ required SliverHitTest hitTest,
}) {
assert(mainAxisOffset != null);
assert(crossAxisOffset != null);
@@ -885,8 +878,8 @@
/// The [mainAxisPosition] and [crossAxisPosition] arguments must not be null.
SliverHitTestEntry(
RenderSliver target, {
- @required this.mainAxisPosition,
- @required this.crossAxisPosition,
+ required this.mainAxisPosition,
+ required this.crossAxisPosition,
}) : assert(mainAxisPosition != null),
assert(crossAxisPosition != null),
super(target);
@@ -936,10 +929,10 @@
/// In a typical list, this does not change as the parent is scrolled.
///
/// Defaults to null.
- double layoutOffset;
+ double? layoutOffset;
@override
- String toString() => 'layoutOffset=${layoutOffset == null ? 'None': layoutOffset.toStringAsFixed(1)}';
+ String toString() => 'layoutOffset=${layoutOffset == null ? 'None': layoutOffset!.toStringAsFixed(1)}';
}
/// Parent data for slivers that have multiple children and that position their
@@ -967,6 +960,7 @@
/// Used to implement [RenderObject.applyPaintTransform] by slivers that use
/// [SliverPhysicalParentData].
void applyPaintTransform(Matrix4 transform) {
+ // Hit test logic relies on this always providing an invertible matrix.
transform.translate(paintOffset.dx, paintOffset.dy);
}
@@ -1147,9 +1141,9 @@
/// [performLayout] or [performResize] functions. If you wish to change the
/// geometry of a sliver outside of those functions, call [markNeedsLayout]
/// instead to schedule a layout of the sliver.
- SliverGeometry get geometry => _geometry;
- SliverGeometry _geometry;
- set geometry(SliverGeometry value) {
+ SliverGeometry? get geometry => _geometry;
+ SliverGeometry? _geometry;
+ set geometry(SliverGeometry? value) {
assert(!(debugDoingThisResize && debugDoingThisLayout));
assert(sizedByParent || !debugDoingThisResize);
assert(() {
@@ -1157,13 +1151,13 @@
(!sizedByParent && debugDoingThisLayout))
return true;
assert(!debugDoingThisResize);
- DiagnosticsNode contract, violation, hint;
+ DiagnosticsNode? contract, violation, hint;
if (debugDoingThisLayout) {
assert(sizedByParent);
violation = ErrorDescription('It appears that the geometry setter was called from performLayout().');
} else {
violation = ErrorDescription('The geometry setter was called from outside layout (neither performResize() nor performLayout() were being run for this object).');
- if (owner != null && owner.debugDoingLayout)
+ if (owner != null && owner!.debugDoingLayout)
hint = ErrorDescription('Only the object itself can set its geometry. It is a contract violation for other objects to set it.');
}
if (sizedByParent)
@@ -1193,17 +1187,16 @@
case Axis.horizontal:
return Rect.fromLTWH(
0.0, 0.0,
- geometry.paintExtent,
+ geometry!.paintExtent,
constraints.crossAxisExtent,
);
case Axis.vertical:
return Rect.fromLTWH(
0.0, 0.0,
constraints.crossAxisExtent,
- geometry.paintExtent,
+ geometry!.paintExtent,
);
}
- return null;
}
@override
@@ -1211,19 +1204,19 @@
@override
void debugAssertDoesMeetConstraints() {
- assert(geometry.debugAssertIsValid(
+ assert(geometry!.debugAssertIsValid(
informationCollector: () sync* {
yield describeForError('The RenderSliver that returned the offending geometry was');
}
));
assert(() {
- if (geometry.paintOrigin + geometry.paintExtent > constraints.remainingPaintExtent) {
+ if (geometry!.paintOrigin + geometry!.paintExtent > constraints.remainingPaintExtent) {
throw FlutterError.fromParts(<DiagnosticsNode>[
ErrorSummary('SliverGeometry has a paintOffset that exceeds the remainingPaintExtent from the constraints.'),
describeForError('The render object whose geometry violates the constraints is the following'),
..._debugCompareFloats(
'remainingPaintExtent', constraints.remainingPaintExtent,
- 'paintOrigin + paintExtent', geometry.paintOrigin + geometry.paintExtent,
+ 'paintOrigin + paintExtent', geometry!.paintOrigin + geometry!.paintExtent,
),
ErrorDescription(
'The paintOrigin and paintExtent must cause the child sliver to paint '
@@ -1290,8 +1283,8 @@
/// The most straight-forward way to implement hit testing for a new sliver
/// render object is to override its [hitTestSelf] and [hitTestChildren]
/// methods.
- bool hitTest(SliverHitTestResult result, { @required double mainAxisPosition, @required double crossAxisPosition }) {
- if (mainAxisPosition >= 0.0 && mainAxisPosition < geometry.hitTestExtent &&
+ bool hitTest(SliverHitTestResult result, { required double mainAxisPosition, required double crossAxisPosition }) {
+ if (mainAxisPosition >= 0.0 && mainAxisPosition < geometry!.hitTestExtent &&
crossAxisPosition >= 0.0 && crossAxisPosition < constraints.crossAxisExtent) {
if (hitTestChildren(result, mainAxisPosition: mainAxisPosition, crossAxisPosition: crossAxisPosition) ||
hitTestSelf(mainAxisPosition: mainAxisPosition, crossAxisPosition: crossAxisPosition)) {
@@ -1314,7 +1307,7 @@
///
/// For a discussion of the semantics of the arguments, see [hitTest].
@protected
- bool hitTestSelf({ @required double mainAxisPosition, @required double crossAxisPosition }) => false;
+ bool hitTestSelf({ required double mainAxisPosition, required double crossAxisPosition }) => false;
/// Override this method to check whether any children are located at the
/// given position.
@@ -1328,7 +1321,7 @@
///
/// For a discussion of the semantics of the arguments, see [hitTest].
@protected
- bool hitTestChildren(SliverHitTestResult result, { @required double mainAxisPosition, @required double crossAxisPosition }) => false;
+ bool hitTestChildren(SliverHitTestResult result, { required double mainAxisPosition, required double crossAxisPosition }) => false;
/// Computes the portion of the region from `from` to `to` that is visible,
/// assuming that only the region from the [SliverConstraints.scrollOffset]
@@ -1347,12 +1340,12 @@
/// function's results will not be consistent.
// This could be a static method but isn't, because it would be less convenient
// to call it from subclasses if it was.
- double calculatePaintOffset(SliverConstraints constraints, { @required double from, @required double to }) {
+ double calculatePaintOffset(SliverConstraints constraints, { required double from, required double to }) {
assert(from <= to);
final double a = constraints.scrollOffset;
final double b = constraints.scrollOffset + constraints.remainingPaintExtent;
// the clamp on the next line is to avoid floating point rounding errors
- return (to.clamp(a, b) - from.clamp(a, b)).clamp(0.0, constraints.remainingPaintExtent) as double;
+ return (to.clamp(a, b) - from.clamp(a, b)).clamp(0.0, constraints.remainingPaintExtent);
}
/// Computes the portion of the region from `from` to `to` that is within
@@ -1363,12 +1356,12 @@
///
/// This method is not useful if there is not a 1:1 relationship between
/// consumed scroll offset and consumed cache extent.
- double calculateCacheOffset(SliverConstraints constraints, { @required double from, @required double to }) {
+ double calculateCacheOffset(SliverConstraints constraints, { required double from, required double to }) {
assert(from <= to);
final double a = constraints.scrollOffset + constraints.cacheOrigin;
final double b = constraints.scrollOffset + constraints.remainingCacheExtent;
// the clamp on the next line is to avoid floating point rounding errors
- return (to.clamp(a, b) - from.clamp(a, b)).clamp(0.0, constraints.remainingCacheExtent) as double;
+ return (to.clamp(a, b) - from.clamp(a, b)).clamp(0.0, constraints.remainingCacheExtent);
}
/// Returns the distance from the leading _visible_ edge of the sliver to the
@@ -1429,7 +1422,7 @@
/// [childMainAxisPosition] gives the distance from the leading _visible_ edge
/// of the sliver whereas [childScrollOffset] gives the distance from sliver's
/// zero scroll offset.
- double childScrollOffset(covariant RenderObject child) {
+ double? childScrollOffset(covariant RenderObject child) {
assert(child.parent == this);
return 0.0;
}
@@ -1456,15 +1449,14 @@
assert(!debugNeedsLayout);
switch (applyGrowthDirectionToAxisDirection(constraints.axisDirection, constraints.growthDirection)) {
case AxisDirection.up:
- return Size(constraints.crossAxisExtent, -geometry.paintExtent);
+ return Size(constraints.crossAxisExtent, -geometry!.paintExtent);
case AxisDirection.right:
- return Size(geometry.paintExtent, constraints.crossAxisExtent);
+ return Size(geometry!.paintExtent, constraints.crossAxisExtent);
case AxisDirection.down:
- return Size(constraints.crossAxisExtent, geometry.paintExtent);
+ return Size(constraints.crossAxisExtent, geometry!.paintExtent);
case AxisDirection.left:
- return Size(-geometry.paintExtent, constraints.crossAxisExtent);
+ return Size(-geometry!.paintExtent, constraints.crossAxisExtent);
}
- return null;
}
/// This returns the absolute [Size] of the sliver.
@@ -1483,12 +1475,11 @@
switch (constraints.axisDirection) {
case AxisDirection.up:
case AxisDirection.down:
- return Size(constraints.crossAxisExtent, geometry.paintExtent);
+ return Size(constraints.crossAxisExtent, geometry!.paintExtent);
case AxisDirection.right:
case AxisDirection.left:
- return Size(geometry.paintExtent, constraints.crossAxisExtent);
+ return Size(geometry!.paintExtent, constraints.crossAxisExtent);
}
- return null;
}
void _debugDrawArrow(Canvas canvas, Paint paint, Offset p0, Offset p1, GrowthDirection direction) {
@@ -1532,13 +1523,13 @@
void debugPaint(PaintingContext context, Offset offset) {
assert(() {
if (debugPaintSizeEnabled) {
- final double strokeWidth = math.min(4.0, geometry.paintExtent / 30.0);
+ final double strokeWidth = math.min(4.0, geometry!.paintExtent / 30.0);
final Paint paint = Paint()
..color = const Color(0xFF33CC33)
..strokeWidth = strokeWidth
..style = PaintingStyle.stroke
..maskFilter = MaskFilter.blur(BlurStyle.solid, strokeWidth);
- final double arrowExtent = geometry.paintExtent;
+ final double arrowExtent = geometry!.paintExtent;
final double padding = math.max(2.0, strokeWidth);
final Canvas canvas = context.canvas;
canvas.drawCircle(
@@ -1646,7 +1637,7 @@
///
/// Calling this for a child that is not visible is not valid.
@protected
- bool hitTestBoxChild(BoxHitTestResult result, RenderBox child, { @required double mainAxisPosition, @required double crossAxisPosition }) {
+ bool hitTestBoxChild(BoxHitTestResult result, RenderBox child, { required double mainAxisPosition, required double crossAxisPosition }) {
final bool rightWayUp = _getRightWayUp(constraints);
double delta = childMainAxisPosition(child);
final double crossAxisDelta = childCrossAxisPosition(child);
@@ -1658,7 +1649,7 @@
case Axis.horizontal:
if (!rightWayUp) {
absolutePosition = child.size.width - absolutePosition;
- delta = geometry.paintExtent - child.size.width - delta;
+ delta = geometry!.paintExtent - child.size.width - delta;
}
paintOffset = Offset(delta, crossAxisDelta);
transformedPosition = Offset(absolutePosition, absoluteCrossAxisPosition);
@@ -1666,7 +1657,7 @@
case Axis.vertical:
if (!rightWayUp) {
absolutePosition = child.size.height - absolutePosition;
- delta = geometry.paintExtent - child.size.height - delta;
+ delta = geometry!.paintExtent - child.size.height - delta;
}
paintOffset = Offset(crossAxisDelta, delta);
transformedPosition = Offset(absoluteCrossAxisPosition, absolutePosition);
@@ -1674,10 +1665,9 @@
}
assert(paintOffset != null);
assert(transformedPosition != null);
- return result.addWithPaintOffset(
- offset: paintOffset,
- position: null, // Manually adapting from sliver to box position above.
- hitTest: (BoxHitTestResult result, Offset _) {
+ return result.addWithOutOfBandPosition(
+ paintOffset: paintOffset,
+ hitTest: (BoxHitTestResult result) {
return child.hitTest(result, position: transformedPosition);
},
);
@@ -1700,12 +1690,12 @@
switch (constraints.axis) {
case Axis.horizontal:
if (!rightWayUp)
- delta = geometry.paintExtent - child.size.width - delta;
+ delta = geometry!.paintExtent - child.size.width - delta;
transform.translate(delta, crossAxisDelta);
break;
case Axis.vertical:
if (!rightWayUp)
- delta = geometry.paintExtent - child.size.height - delta;
+ delta = geometry!.paintExtent - child.size.height - delta;
transform.translate(crossAxisDelta, delta);
break;
}
@@ -1728,7 +1718,7 @@
abstract class RenderSliverSingleBoxAdapter extends RenderSliver with RenderObjectWithChildMixin<RenderBox>, RenderSliverHelpers {
/// Creates a [RenderSliver] that wraps a [RenderBox].
RenderSliverSingleBoxAdapter({
- RenderBox child,
+ RenderBox? child,
}) {
this.child = child;
}
@@ -1765,10 +1755,10 @@
}
@override
- bool hitTestChildren(SliverHitTestResult result, { @required double mainAxisPosition, @required double crossAxisPosition }) {
- assert(geometry.hitTestExtent > 0.0);
+ bool hitTestChildren(SliverHitTestResult result, { required double mainAxisPosition, required double crossAxisPosition }) {
+ assert(geometry!.hitTestExtent > 0.0);
if (child != null)
- return hitTestBoxChild(BoxHitTestResult.wrap(result), child, mainAxisPosition: mainAxisPosition, crossAxisPosition: crossAxisPosition);
+ return hitTestBoxChild(BoxHitTestResult.wrap(result), child!, mainAxisPosition: mainAxisPosition, crossAxisPosition: crossAxisPosition);
return false;
}
@@ -1787,9 +1777,9 @@
@override
void paint(PaintingContext context, Offset offset) {
- if (child != null && geometry.visible) {
- final SliverPhysicalParentData childParentData = child.parentData as SliverPhysicalParentData;
- context.paintChild(child, offset + childParentData.paintOffset);
+ if (child != null && geometry!.visible) {
+ final SliverPhysicalParentData childParentData = child!.parentData as SliverPhysicalParentData;
+ context.paintChild(child!, offset + childParentData.paintOffset);
}
}
}
@@ -1809,7 +1799,7 @@
class RenderSliverToBoxAdapter extends RenderSliverSingleBoxAdapter {
/// Creates a [RenderSliver] that wraps a [RenderBox].
RenderSliverToBoxAdapter({
- RenderBox child,
+ RenderBox? child,
}) : super(child: child);
@override
@@ -1819,14 +1809,14 @@
return;
}
final SliverConstraints constraints = this.constraints;
- child.layout(constraints.asBoxConstraints(), parentUsesSize: true);
+ child!.layout(constraints.asBoxConstraints(), parentUsesSize: true);
double childExtent;
switch (constraints.axis) {
case Axis.horizontal:
- childExtent = child.size.width;
+ childExtent = child!.size.width;
break;
case Axis.vertical:
- childExtent = child.size.height;
+ childExtent = child!.size.height;
break;
}
assert(childExtent != null);
@@ -1843,6 +1833,6 @@
hitTestExtent: paintedChildSize,
hasVisualOverflow: childExtent > constraints.remainingPaintExtent || constraints.scrollOffset > 0.0,
);
- setChildParentData(child, constraints, geometry);
+ setChildParentData(child!, constraints, geometry!);
}
}
diff --git a/packages/flutter/lib/src/rendering/sliver_fill.dart b/packages/flutter/lib/src/rendering/sliver_fill.dart
index 92448d4..8907590 100644
--- a/packages/flutter/lib/src/rendering/sliver_fill.dart
+++ b/packages/flutter/lib/src/rendering/sliver_fill.dart
@@ -2,12 +2,8 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-// @dart = 2.8
-
import 'dart:math' as math;
-import 'package:flutter/foundation.dart';
-
import 'box.dart';
import 'object.dart';
import 'sliver.dart';
@@ -35,7 +31,7 @@
///
/// The [childManager] argument must not be null.
RenderSliverFillViewport({
- @required RenderSliverBoxChildManager childManager,
+ required RenderSliverBoxChildManager childManager,
double viewportFraction = 1.0,
}) : assert(viewportFraction != null),
assert(viewportFraction > 0.0),
@@ -85,7 +81,7 @@
class RenderSliverFillRemainingWithScrollable extends RenderSliverSingleBoxAdapter {
/// Creates a [RenderSliver] that wraps a scrollable [RenderBox] which is
/// sized to fit the remaining space in the viewport.
- RenderSliverFillRemainingWithScrollable({ RenderBox child }) : super(child: child);
+ RenderSliverFillRemainingWithScrollable({ RenderBox? child }) : super(child: child);
@override
void performLayout() {
@@ -94,7 +90,7 @@
final double extent = constraints.remainingPaintExtent - math.min(constraints.overlap, 0.0);
if (child != null)
- child.layout(constraints.asBoxConstraints(
+ child!.layout(constraints.asBoxConstraints(
minExtent: extent,
maxExtent: extent,
));
@@ -109,7 +105,7 @@
hasVisualOverflow: extent > constraints.remainingPaintExtent || constraints.scrollOffset > 0.0,
);
if (child != null)
- setChildParentData(child, constraints, geometry);
+ setChildParentData(child!, constraints, geometry!);
}
}
@@ -136,7 +132,7 @@
class RenderSliverFillRemaining extends RenderSliverSingleBoxAdapter {
/// Creates a [RenderSliver] that wraps a non-scrollable [RenderBox] which is
/// sized to fit the remaining space in the viewport.
- RenderSliverFillRemaining({ RenderBox child }) : super(child: child);
+ RenderSliverFillRemaining({ RenderBox? child }) : super(child: child);
@override
void performLayout() {
@@ -149,10 +145,10 @@
double childExtent;
switch (constraints.axis) {
case Axis.horizontal:
- childExtent = child.getMaxIntrinsicWidth(constraints.crossAxisExtent);
+ childExtent = child!.getMaxIntrinsicWidth(constraints.crossAxisExtent);
break;
case Axis.vertical:
- childExtent = child.getMaxIntrinsicHeight(constraints.crossAxisExtent);
+ childExtent = child!.getMaxIntrinsicHeight(constraints.crossAxisExtent);
break;
}
@@ -160,7 +156,7 @@
// that instead of potentially cutting off the child. This allows us to
// safely specify a maxExtent.
extent = math.max(extent, childExtent);
- child.layout(constraints.asBoxConstraints(
+ child!.layout(constraints.asBoxConstraints(
minExtent: extent,
maxExtent: extent,
));
@@ -182,7 +178,7 @@
hasVisualOverflow: extent > constraints.remainingPaintExtent || constraints.scrollOffset > 0.0,
);
if (child != null)
- setChildParentData(child, constraints, geometry);
+ setChildParentData(child!, constraints, geometry!);
}
}
@@ -209,7 +205,7 @@
class RenderSliverFillRemainingAndOverscroll extends RenderSliverSingleBoxAdapter {
/// Creates a [RenderSliver] that wraps a non-scrollable [RenderBox] which is
/// sized to fit the remaining space plus any overscroll in the viewport.
- RenderSliverFillRemainingAndOverscroll({ RenderBox child }) : super(child: child);
+ RenderSliverFillRemainingAndOverscroll({ RenderBox? child }) : super(child: child);
@override
void performLayout() {
@@ -225,10 +221,10 @@
double childExtent;
switch (constraints.axis) {
case Axis.horizontal:
- childExtent = child.getMaxIntrinsicWidth(constraints.crossAxisExtent);
+ childExtent = child!.getMaxIntrinsicWidth(constraints.crossAxisExtent);
break;
case Axis.vertical:
- childExtent = child.getMaxIntrinsicHeight(constraints.crossAxisExtent);
+ childExtent = child!.getMaxIntrinsicHeight(constraints.crossAxisExtent);
break;
}
@@ -240,7 +236,7 @@
// size or overscrolling at the top of the scrollable (rather than at the
// end where this sliver is).
maxExtent = math.max(extent, maxExtent);
- child.layout(constraints.asBoxConstraints(minExtent: extent, maxExtent: maxExtent));
+ child!.layout(constraints.asBoxConstraints(minExtent: extent, maxExtent: maxExtent));
}
assert(extent.isFinite,
@@ -259,6 +255,6 @@
hasVisualOverflow: extent > constraints.remainingPaintExtent || constraints.scrollOffset > 0.0,
);
if (child != null)
- setChildParentData(child, constraints, geometry);
+ setChildParentData(child!, constraints, geometry!);
}
}
diff --git a/packages/flutter/lib/src/rendering/sliver_fixed_extent_list.dart b/packages/flutter/lib/src/rendering/sliver_fixed_extent_list.dart
index 97ec874..5e432a2 100644
--- a/packages/flutter/lib/src/rendering/sliver_fixed_extent_list.dart
+++ b/packages/flutter/lib/src/rendering/sliver_fixed_extent_list.dart
@@ -2,8 +2,6 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-// @dart = 2.8
-
import 'dart:math' as math;
import 'package:flutter/foundation.dart';
@@ -42,7 +40,7 @@
///
/// The [childManager] argument must not be null.
RenderSliverFixedExtentBoxAdaptor({
- @required RenderSliverBoxChildManager childManager,
+ required RenderSliverBoxChildManager childManager,
}) : super(childManager: childManager);
/// The main-axis extent of each item.
@@ -105,10 +103,10 @@
@protected
double estimateMaxScrollOffset(
SliverConstraints constraints, {
- int firstIndex,
- int lastIndex,
- double leadingScrollOffset,
- double trailingScrollOffset,
+ int? firstIndex,
+ int? lastIndex,
+ double? leadingScrollOffset,
+ double? trailingScrollOffset,
}) {
return childManager.estimateMaxScrollOffset(
constraints,
@@ -145,7 +143,7 @@
}
int _calculateLeadingGarbage(int firstIndex) {
- RenderBox walker = firstChild;
+ RenderBox? walker = firstChild;
int leadingGarbage = 0;
while(walker != null && indexOf(walker) < firstIndex){
leadingGarbage += 1;
@@ -155,7 +153,7 @@
}
int _calculateTrailingGarbage(int targetLastIndex) {
- RenderBox walker = lastChild;
+ RenderBox? walker = lastChild;
int trailingGarbage = 0;
while(walker != null && indexOf(walker) > targetLastIndex){
trailingGarbage += 1;
@@ -184,12 +182,12 @@
);
final int firstIndex = getMinChildIndexForScrollOffset(scrollOffset, itemExtent);
- final int targetLastIndex = targetEndScrollOffset.isFinite ?
+ final int? targetLastIndex = targetEndScrollOffset.isFinite ?
getMaxChildIndexForScrollOffset(targetEndScrollOffset, itemExtent) : null;
if (firstChild != null) {
final int leadingGarbage = _calculateLeadingGarbage(firstIndex);
- final int trailingGarbage = _calculateTrailingGarbage(targetLastIndex);
+ final int trailingGarbage = _calculateTrailingGarbage(targetLastIndex!);
collectGarbage(leadingGarbage, trailingGarbage);
} else {
collectGarbage(0, 0);
@@ -202,7 +200,10 @@
double max;
if (childManager.childCount != null) {
max = computeMaxScrollOffset(constraints, itemExtent);
- } else if (firstIndex <= 0) {
+ // TODO(ianh): null-aware flow analysis flags the next two
+ // branches as entirely dead code, and it's hard to argue with
+ // its logic.
+ } else if (firstIndex <= 0) { // ignore: dead_code
max = 0.0;
} else {
// We will have to find it manually.
@@ -227,10 +228,10 @@
}
}
- RenderBox trailingChildWithLayout;
+ RenderBox? trailingChildWithLayout;
- for (int index = indexOf(firstChild) - 1; index >= firstIndex; --index) {
- final RenderBox child = insertAndLayoutLeadingChild(childConstraints);
+ for (int index = indexOf(firstChild!) - 1; index >= firstIndex; --index) {
+ final RenderBox? child = insertAndLayoutLeadingChild(childConstraints);
if (child == null) {
// Items before the previously first child are no longer present.
// Reset the scroll offset to offset all items prior and up to the
@@ -245,15 +246,15 @@
}
if (trailingChildWithLayout == null) {
- firstChild.layout(childConstraints);
- final SliverMultiBoxAdaptorParentData childParentData = firstChild.parentData as SliverMultiBoxAdaptorParentData;
+ firstChild!.layout(childConstraints);
+ final SliverMultiBoxAdaptorParentData childParentData = firstChild!.parentData as SliverMultiBoxAdaptorParentData;
childParentData.layoutOffset = indexToLayoutOffset(itemExtent, firstIndex);
trailingChildWithLayout = firstChild;
}
double estimatedMaxScrollOffset = double.infinity;
- for (int index = indexOf(trailingChildWithLayout) + 1; targetLastIndex == null || index <= targetLastIndex; ++index) {
- RenderBox child = childAfter(trailingChildWithLayout);
+ for (int index = indexOf(trailingChildWithLayout!) + 1; targetLastIndex == null || index <= targetLastIndex; ++index) {
+ RenderBox? child = childAfter(trailingChildWithLayout!);
if (child == null || indexOf(child) != index) {
child = insertAndLayoutChild(childConstraints, after: trailingChildWithLayout);
if (child == null) {
@@ -268,16 +269,16 @@
assert(child != null);
final SliverMultiBoxAdaptorParentData childParentData = child.parentData as SliverMultiBoxAdaptorParentData;
assert(childParentData.index == index);
- childParentData.layoutOffset = indexToLayoutOffset(itemExtent, childParentData.index);
+ childParentData.layoutOffset = indexToLayoutOffset(itemExtent, childParentData.index!);
}
- final int lastIndex = indexOf(lastChild);
+ final int lastIndex = indexOf(lastChild!);
final double leadingScrollOffset = indexToLayoutOffset(itemExtent, firstIndex);
final double trailingScrollOffset = indexToLayoutOffset(itemExtent, lastIndex + 1);
- assert(firstIndex == 0 || childScrollOffset(firstChild) - scrollOffset <= precisionErrorTolerance);
+ assert(firstIndex == 0 || childScrollOffset(firstChild!)! - scrollOffset <= precisionErrorTolerance);
assert(debugAssertChildListIsNonEmptyAndContiguous());
- assert(indexOf(firstChild) == firstIndex);
+ assert(indexOf(firstChild!) == firstIndex);
assert(targetLastIndex == null || lastIndex <= targetLastIndex);
estimatedMaxScrollOffset = math.min(
@@ -304,7 +305,7 @@
);
final double targetEndScrollOffsetForPaint = constraints.scrollOffset + constraints.remainingPaintExtent;
- final int targetLastIndexForPaint = targetEndScrollOffsetForPaint.isFinite ?
+ final int? targetLastIndexForPaint = targetEndScrollOffsetForPaint.isFinite ?
getMaxChildIndexForScrollOffset(targetEndScrollOffsetForPaint, itemExtent) : null;
geometry = SliverGeometry(
scrollExtent: estimatedMaxScrollOffset,
@@ -350,8 +351,8 @@
///
/// The [childManager] argument must not be null.
RenderSliverFixedExtentList({
- @required RenderSliverBoxChildManager childManager,
- double itemExtent,
+ required RenderSliverBoxChildManager childManager,
+ required double itemExtent,
}) : _itemExtent = itemExtent,
super(childManager: childManager);
diff --git a/packages/flutter/lib/src/rendering/sliver_grid.dart b/packages/flutter/lib/src/rendering/sliver_grid.dart
index 19622d1..f21570d 100644
--- a/packages/flutter/lib/src/rendering/sliver_grid.dart
+++ b/packages/flutter/lib/src/rendering/sliver_grid.dart
@@ -2,8 +2,6 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-// @dart = 2.8
-
import 'dart:math' as math;
import 'package:flutter/foundation.dart';
@@ -27,10 +25,10 @@
class SliverGridGeometry {
/// Creates an object that describes the placement of a child in a [RenderSliverGrid].
const SliverGridGeometry({
- @required this.scrollOffset,
- @required this.crossAxisOffset,
- @required this.mainAxisExtent,
- @required this.crossAxisExtent,
+ required this.scrollOffset,
+ required this.crossAxisOffset,
+ required this.mainAxisExtent,
+ required this.crossAxisExtent,
});
/// The scroll offset of the leading edge of the child relative to the leading
@@ -151,12 +149,12 @@
/// All of the arguments must not be null and must not be negative. The
/// `crossAxisCount` argument must be greater than zero.
const SliverGridRegularTileLayout({
- @required this.crossAxisCount,
- @required this.mainAxisStride,
- @required this.crossAxisStride,
- @required this.childMainAxisExtent,
- @required this.childCrossAxisExtent,
- @required this.reverseCrossAxis,
+ required this.crossAxisCount,
+ required this.mainAxisStride,
+ required this.crossAxisStride,
+ required this.childMainAxisExtent,
+ required this.childCrossAxisExtent,
+ required this.reverseCrossAxis,
}) : assert(crossAxisCount != null && crossAxisCount > 0),
assert(mainAxisStride != null && mainAxisStride >= 0),
assert(crossAxisStride != null && crossAxisStride >= 0),
@@ -296,7 +294,7 @@
/// `crossAxisSpacing` arguments must not be negative. The `crossAxisCount`
/// and `childAspectRatio` arguments must be greater than zero.
const SliverGridDelegateWithFixedCrossAxisCount({
- @required this.crossAxisCount,
+ required this.crossAxisCount,
this.mainAxisSpacing = 0.0,
this.crossAxisSpacing = 0.0,
this.childAspectRatio = 1.0,
@@ -383,7 +381,7 @@
/// [mainAxisSpacing], and [crossAxisSpacing] arguments must not be negative.
/// The [childAspectRatio] argument must be greater than zero.
const SliverGridDelegateWithMaxCrossAxisExtent({
- @required this.maxCrossAxisExtent,
+ required this.maxCrossAxisExtent,
this.mainAxisSpacing = 0.0,
this.crossAxisSpacing = 0.0,
this.childAspectRatio = 1.0,
@@ -457,7 +455,7 @@
/// the parent to the left-most edge of the child. If the scroll axis is
/// horizontal, this offset is from the top-most edge of the parent to the
/// top-most edge of the child.
- double crossAxisOffset;
+ double? crossAxisOffset;
@override
String toString() => 'crossAxisOffset=$crossAxisOffset; ${super.toString()}';
@@ -481,8 +479,8 @@
///
/// The [childManager] and [gridDelegate] arguments must not be null.
RenderSliverGrid({
- @required RenderSliverBoxChildManager childManager,
- @required SliverGridDelegate gridDelegate,
+ required RenderSliverBoxChildManager childManager,
+ required SliverGridDelegate gridDelegate,
}) : assert(gridDelegate != null),
_gridDelegate = gridDelegate,
super(childManager: childManager);
@@ -509,7 +507,7 @@
@override
double childCrossAxisPosition(RenderBox child) {
final SliverGridParentData childParentData = child.parentData as SliverGridParentData;
- return childParentData.crossAxisOffset;
+ return childParentData.crossAxisOffset!;
}
@override
@@ -527,16 +525,16 @@
final SliverGridLayout layout = _gridDelegate.getLayout(constraints);
final int firstIndex = layout.getMinChildIndexForScrollOffset(scrollOffset);
- final int targetLastIndex = targetEndScrollOffset.isFinite ?
+ final int? targetLastIndex = targetEndScrollOffset.isFinite ?
layout.getMaxChildIndexForScrollOffset(targetEndScrollOffset) : null;
if (firstChild != null) {
- final int oldFirstIndex = indexOf(firstChild);
- final int oldLastIndex = indexOf(lastChild);
- final int leadingGarbage = (firstIndex - oldFirstIndex).clamp(0, childCount) as int;
+ final int oldFirstIndex = indexOf(firstChild!);
+ final int oldLastIndex = indexOf(lastChild!);
+ final int leadingGarbage = (firstIndex - oldFirstIndex).clamp(0, childCount);
final int trailingGarbage = targetLastIndex == null
? 0
- : ((oldLastIndex - targetLastIndex).clamp(0, childCount) as int);
+ : (oldLastIndex - targetLastIndex).clamp(0, childCount);
collectGarbage(leadingGarbage, trailingGarbage);
} else {
collectGarbage(0, 0);
@@ -559,13 +557,13 @@
}
}
- RenderBox trailingChildWithLayout;
+ RenderBox? trailingChildWithLayout;
- for (int index = indexOf(firstChild) - 1; index >= firstIndex; --index) {
+ for (int index = indexOf(firstChild!) - 1; index >= firstIndex; --index) {
final SliverGridGeometry gridGeometry = layout.getGeometryForChildIndex(index);
final RenderBox child = insertAndLayoutLeadingChild(
gridGeometry.getBoxConstraints(constraints),
- );
+ )!;
final SliverGridParentData childParentData = child.parentData as SliverGridParentData;
childParentData.layoutOffset = gridGeometry.scrollOffset;
childParentData.crossAxisOffset = gridGeometry.crossAxisOffset;
@@ -575,17 +573,17 @@
}
if (trailingChildWithLayout == null) {
- firstChild.layout(firstChildGridGeometry.getBoxConstraints(constraints));
- final SliverGridParentData childParentData = firstChild.parentData as SliverGridParentData;
+ firstChild!.layout(firstChildGridGeometry.getBoxConstraints(constraints));
+ final SliverGridParentData childParentData = firstChild!.parentData as SliverGridParentData;
childParentData.layoutOffset = firstChildGridGeometry.scrollOffset;
childParentData.crossAxisOffset = firstChildGridGeometry.crossAxisOffset;
trailingChildWithLayout = firstChild;
}
- for (int index = indexOf(trailingChildWithLayout) + 1; targetLastIndex == null || index <= targetLastIndex; ++index) {
+ for (int index = indexOf(trailingChildWithLayout!) + 1; targetLastIndex == null || index <= targetLastIndex; ++index) {
final SliverGridGeometry gridGeometry = layout.getGeometryForChildIndex(index);
final BoxConstraints childConstraints = gridGeometry.getBoxConstraints(constraints);
- RenderBox child = childAfter(trailingChildWithLayout);
+ RenderBox? child = childAfter(trailingChildWithLayout!);
if (child == null || indexOf(child) != index) {
child = insertAndLayoutChild(childConstraints, after: trailingChildWithLayout);
if (child == null) {
@@ -604,11 +602,11 @@
trailingScrollOffset = math.max(trailingScrollOffset, gridGeometry.trailingScrollOffset);
}
- final int lastIndex = indexOf(lastChild);
+ final int lastIndex = indexOf(lastChild!);
- assert(childScrollOffset(firstChild) <= scrollOffset);
+ assert(childScrollOffset(firstChild!)! <= scrollOffset);
assert(debugAssertChildListIsNonEmptyAndContiguous());
- assert(indexOf(firstChild) == firstIndex);
+ assert(indexOf(firstChild!) == firstIndex);
assert(targetLastIndex == null || lastIndex <= targetLastIndex);
final double estimatedTotalExtent = childManager.estimateMaxScrollOffset(
diff --git a/packages/flutter/lib/src/rendering/sliver_list.dart b/packages/flutter/lib/src/rendering/sliver_list.dart
index e47babf..0cf665c 100644
--- a/packages/flutter/lib/src/rendering/sliver_list.dart
+++ b/packages/flutter/lib/src/rendering/sliver_list.dart
@@ -2,8 +2,6 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-// @dart = 2.8
-
import 'package:flutter/foundation.dart';
import 'box.dart';
@@ -41,7 +39,7 @@
///
/// The [childManager] argument must not be null.
RenderSliverList({
- @required RenderSliverBoxChildManager childManager,
+ required RenderSliverBoxChildManager childManager,
}) : super(childManager: childManager);
@override
@@ -91,9 +89,9 @@
// These variables track the range of children that we have laid out. Within
// this range, the children have consecutive indices. Outside this range,
// it's possible for a child to get removed without notice.
- RenderBox leadingChildWithLayout, trailingChildWithLayout;
+ RenderBox? leadingChildWithLayout, trailingChildWithLayout;
- RenderBox earliestUsefulChild = firstChild;
+ RenderBox? earliestUsefulChild = firstChild;
// A firstChild with null layout offset is likely a result of children
// reordering.
@@ -101,10 +99,10 @@
// We rely on firstChild to have accurate layout offset. In the case of null
// layout offset, we have to find the first child that has valid layout
// offset.
- if (childScrollOffset(firstChild) == null) {
+ if (childScrollOffset(firstChild!) == null) {
int leadingChildrenWithoutLayoutOffset = 0;
- while (childScrollOffset(earliestUsefulChild) == null) {
- earliestUsefulChild = childAfter(firstChild);
+ while (childScrollOffset(earliestUsefulChild!) == null) {
+ earliestUsefulChild = childAfter(firstChild!);
leadingChildrenWithoutLayoutOffset += 1;
}
// We should be able to destroy children with null layout offset safely,
@@ -115,20 +113,20 @@
// Find the last child that is at or before the scrollOffset.
earliestUsefulChild = firstChild;
- for (double earliestScrollOffset = childScrollOffset(earliestUsefulChild);
+ for (double earliestScrollOffset = childScrollOffset(earliestUsefulChild!)!;
earliestScrollOffset > scrollOffset;
- earliestScrollOffset = childScrollOffset(earliestUsefulChild)) {
+ earliestScrollOffset = childScrollOffset(earliestUsefulChild)!) {
// We have to add children before the earliestUsefulChild.
earliestUsefulChild = insertAndLayoutLeadingChild(childConstraints, parentUsesSize: true);
if (earliestUsefulChild == null) {
- final SliverMultiBoxAdaptorParentData childParentData = firstChild.parentData as SliverMultiBoxAdaptorParentData;
+ final SliverMultiBoxAdaptorParentData childParentData = firstChild!.parentData as SliverMultiBoxAdaptorParentData;
childParentData.layoutOffset = 0.0;
if (scrollOffset == 0.0) {
// insertAndLayoutLeadingChild only lays out the children before
// firstChild. In this case, nothing has been laid out. We have
// to lay out firstChild manually.
- firstChild.layout(childConstraints, parentUsesSize: true);
+ firstChild!.layout(childConstraints, parentUsesSize: true);
earliestUsefulChild = firstChild;
leadingChildWithLayout = earliestUsefulChild;
trailingChildWithLayout ??= earliestUsefulChild;
@@ -144,7 +142,7 @@
}
}
- final double firstChildScrollOffset = earliestScrollOffset - paintExtentOf(firstChild);
+ final double firstChildScrollOffset = earliestScrollOffset - paintExtentOf(firstChild!);
// firstChildScrollOffset may contain double precision error
if (firstChildScrollOffset < -precisionErrorTolerance) {
// Let's assume there is no child before the first child. We will
@@ -152,7 +150,7 @@
geometry = SliverGeometry(
scrollOffsetCorrection: -firstChildScrollOffset,
);
- final SliverMultiBoxAdaptorParentData childParentData = firstChild.parentData as SliverMultiBoxAdaptorParentData;
+ final SliverMultiBoxAdaptorParentData childParentData = firstChild!.parentData as SliverMultiBoxAdaptorParentData;
childParentData.layoutOffset = 0.0;
return;
}
@@ -164,22 +162,22 @@
trailingChildWithLayout ??= earliestUsefulChild;
}
- assert(childScrollOffset(firstChild) > -precisionErrorTolerance);
+ assert(childScrollOffset(firstChild!)! > -precisionErrorTolerance);
// If the scroll offset is at zero, we should make sure we are
// actually at the beginning of the list.
if (scrollOffset < precisionErrorTolerance) {
// We iterate from the firstChild in case the leading child has a 0 paint
// extent.
- while (indexOf(firstChild) > 0) {
- final double earliestScrollOffset = childScrollOffset(firstChild);
+ while (indexOf(firstChild!) > 0) {
+ final double earliestScrollOffset = childScrollOffset(firstChild!)!;
// We correct one child at a time. If there are more children before
// the earliestUsefulChild, we will correct it once the scroll offset
// reaches zero again.
earliestUsefulChild = insertAndLayoutLeadingChild(childConstraints, parentUsesSize: true);
assert(earliestUsefulChild != null);
- final double firstChildScrollOffset = earliestScrollOffset - paintExtentOf(firstChild);
- final SliverMultiBoxAdaptorParentData childParentData = firstChild.parentData as SliverMultiBoxAdaptorParentData;
+ final double firstChildScrollOffset = earliestScrollOffset - paintExtentOf(firstChild!);
+ final SliverMultiBoxAdaptorParentData childParentData = firstChild!.parentData as SliverMultiBoxAdaptorParentData;
childParentData.layoutOffset = 0.0;
// We only need to correct if the leading child actually has a
// paint extent.
@@ -200,11 +198,11 @@
// scroll offset.
assert(earliestUsefulChild == firstChild);
- assert(childScrollOffset(earliestUsefulChild) <= scrollOffset);
+ assert(childScrollOffset(earliestUsefulChild!)! <= scrollOffset);
// Make sure we've laid out at least one child.
if (leadingChildWithLayout == null) {
- earliestUsefulChild.layout(childConstraints, parentUsesSize: true);
+ earliestUsefulChild!.layout(childConstraints, parentUsesSize: true);
leadingChildWithLayout = earliestUsefulChild;
trailingChildWithLayout = earliestUsefulChild;
}
@@ -215,20 +213,20 @@
// that some children beyond that one have also been laid out.
bool inLayoutRange = true;
- RenderBox child = earliestUsefulChild;
- int index = indexOf(child);
- double endScrollOffset = childScrollOffset(child) + paintExtentOf(child);
+ RenderBox? child = earliestUsefulChild;
+ int index = indexOf(child!);
+ double endScrollOffset = childScrollOffset(child)! + paintExtentOf(child);
bool advance() { // returns true if we advanced, false if we have no more children
// This function is used in two different places below, to avoid code duplication.
assert(child != null);
if (child == trailingChildWithLayout)
inLayoutRange = false;
- child = childAfter(child);
+ child = childAfter(child!);
if (child == null)
inLayoutRange = false;
index += 1;
if (!inLayoutRange) {
- if (child == null || indexOf(child) != index) {
+ if (child == null || indexOf(child!) != index) {
// We are missing a child. Insert it (and lay it out) if possible.
child = insertAndLayoutChild(childConstraints,
after: trailingChildWithLayout,
@@ -240,15 +238,15 @@
}
} else {
// Lay out the child.
- child.layout(childConstraints, parentUsesSize: true);
+ child!.layout(childConstraints, parentUsesSize: true);
}
trailingChildWithLayout = child;
}
assert(child != null);
- final SliverMultiBoxAdaptorParentData childParentData = child.parentData as SliverMultiBoxAdaptorParentData;
+ final SliverMultiBoxAdaptorParentData childParentData = child!.parentData as SliverMultiBoxAdaptorParentData;
childParentData.layoutOffset = endScrollOffset;
assert(childParentData.index == index);
- endScrollOffset = childScrollOffset(child) + paintExtentOf(child);
+ endScrollOffset = childScrollOffset(child!)! + paintExtentOf(child!);
return true;
}
@@ -261,7 +259,7 @@
// we want to make sure we keep the last child around so we know the end scroll offset
collectGarbage(leadingGarbage - 1, 0);
assert(firstChild == lastChild);
- final double extent = childScrollOffset(lastChild) + paintExtentOf(lastChild);
+ final double extent = childScrollOffset(lastChild!)! + paintExtentOf(lastChild!);
geometry = SliverGeometry(
scrollExtent: extent,
paintExtent: 0.0,
@@ -281,10 +279,10 @@
// Finally count up all the remaining children and label them as garbage.
if (child != null) {
- child = childAfter(child);
+ child = childAfter(child!);
while (child != null) {
trailingGarbage += 1;
- child = childAfter(child);
+ child = childAfter(child!);
}
}
@@ -300,21 +298,21 @@
} else {
estimatedMaxScrollOffset = childManager.estimateMaxScrollOffset(
constraints,
- firstIndex: indexOf(firstChild),
- lastIndex: indexOf(lastChild),
- leadingScrollOffset: childScrollOffset(firstChild),
+ firstIndex: indexOf(firstChild!),
+ lastIndex: indexOf(lastChild!),
+ leadingScrollOffset: childScrollOffset(firstChild!),
trailingScrollOffset: endScrollOffset,
);
- assert(estimatedMaxScrollOffset >= endScrollOffset - childScrollOffset(firstChild));
+ assert(estimatedMaxScrollOffset >= endScrollOffset - childScrollOffset(firstChild!)!);
}
final double paintExtent = calculatePaintOffset(
constraints,
- from: childScrollOffset(firstChild),
+ from: childScrollOffset(firstChild!)!,
to: endScrollOffset,
);
final double cacheExtent = calculateCacheOffset(
constraints,
- from: childScrollOffset(firstChild),
+ from: childScrollOffset(firstChild!)!,
to: endScrollOffset,
);
final double targetEndScrollOffsetForPaint = constraints.scrollOffset + constraints.remainingPaintExtent;
diff --git a/packages/flutter/lib/src/rendering/sliver_multi_box_adaptor.dart b/packages/flutter/lib/src/rendering/sliver_multi_box_adaptor.dart
index 666bbb5..0113599 100644
--- a/packages/flutter/lib/src/rendering/sliver_multi_box_adaptor.dart
+++ b/packages/flutter/lib/src/rendering/sliver_multi_box_adaptor.dart
@@ -2,8 +2,6 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-// @dart = 2.8
-
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:vector_math/vector_math_64.dart';
@@ -44,7 +42,7 @@
/// the [RenderSliverMultiBoxAdaptor] object if they were not created during
/// this frame and have not yet been updated during this frame. It is not
/// valid to add any other children to this render object.
- void createChild(int index, { @required RenderBox after });
+ void createChild(int index, { required RenderBox? after });
/// Remove the given child from the child list.
///
@@ -64,10 +62,10 @@
/// index.
double estimateMaxScrollOffset(
SliverConstraints constraints, {
- int firstIndex,
- int lastIndex,
- double leadingScrollOffset,
- double trailingScrollOffset,
+ int? firstIndex,
+ int? lastIndex,
+ double? leadingScrollOffset,
+ double? trailingScrollOffset,
});
/// Called to obtain a precise measure of the total number of children.
@@ -146,7 +144,7 @@
/// Parent data structure used by [RenderSliverMultiBoxAdaptor].
class SliverMultiBoxAdaptorParentData extends SliverLogicalParentData with ContainerParentDataMixin<RenderBox>, KeepAliveParentDataMixin {
/// The index of this child according to the [RenderSliverBoxChildManager].
- int index;
+ int? index;
@override
bool get keptAlive => _keptAlive;
@@ -189,7 +187,7 @@
///
/// The [childManager] argument must not be null.
RenderSliverMultiBoxAdaptor({
- @required RenderSliverBoxChildManager childManager,
+ required RenderSliverBoxChildManager childManager,
}) : assert(childManager != null),
_childManager = childManager {
assert(() {
@@ -217,7 +215,7 @@
/// The nodes being kept alive despite not being visible.
final Map<int, RenderBox> _keepAliveBucket = <int, RenderBox>{};
- List<RenderBox> _debugDanglingKeepAlives;
+ late List<RenderBox> _debugDanglingKeepAlives;
/// Indicates whether integrity check is enabled.
///
@@ -253,7 +251,7 @@
/// This has no effect in release builds.
bool _debugVerifyChildOrder(){
if (_debugChildIntegrityEnabled) {
- RenderBox child = firstChild;
+ RenderBox? child = firstChild;
int index;
while (child != null) {
index = indexOf(child);
@@ -265,7 +263,7 @@
}
@override
- void insert(RenderBox child, { RenderBox after }) {
+ void insert(RenderBox child, { RenderBox? after }) {
assert(!_keepAliveBucket.containsValue(child));
super.insert(child, after: after);
assert(firstChild != null);
@@ -273,7 +271,7 @@
}
@override
- void move(RenderBox child, { RenderBox after }) {
+ void move(RenderBox child, { RenderBox? after }) {
// There are two scenarios:
//
// 1. The child is not keptAlive.
@@ -307,10 +305,10 @@
// removed by updateChild. Thus, it is ok to overwrite it.
assert(() {
if (_keepAliveBucket.containsKey(childParentData.index))
- _debugDanglingKeepAlives.add(_keepAliveBucket[childParentData.index]);
+ _debugDanglingKeepAlives.add(_keepAliveBucket[childParentData.index]!);
return true;
}());
- _keepAliveBucket[childParentData.index] = child;
+ _keepAliveBucket[childParentData.index!] = child;
}
}
@@ -337,11 +335,11 @@
_keepAliveBucket.clear();
}
- void _createOrObtainChild(int index, { RenderBox after }) {
+ void _createOrObtainChild(int index, { required RenderBox? after }) {
invokeLayoutCallback<SliverConstraints>((SliverConstraints constraints) {
assert(constraints == this.constraints);
if (_keepAliveBucket.containsKey(index)) {
- final RenderBox child = _keepAliveBucket.remove(index);
+ final RenderBox child = _keepAliveBucket.remove(index)!;
final SliverMultiBoxAdaptorParentData childParentData = child.parentData as SliverMultiBoxAdaptorParentData;
assert(childParentData._keptAlive);
dropChild(child);
@@ -359,7 +357,7 @@
if (childParentData.keepAlive) {
assert(!childParentData._keptAlive);
remove(child);
- _keepAliveBucket[childParentData.index] = child;
+ _keepAliveBucket[childParentData.index!] = child;
child.parentData = childParentData;
super.adoptChild(child);
childParentData._keptAlive = true;
@@ -425,8 +423,8 @@
_createOrObtainChild(index, after: null);
if (firstChild != null) {
assert(firstChild == lastChild);
- assert(indexOf(firstChild) == index);
- final SliverMultiBoxAdaptorParentData firstChildParentData = firstChild.parentData as SliverMultiBoxAdaptorParentData;
+ assert(indexOf(firstChild!) == index);
+ final SliverMultiBoxAdaptorParentData firstChildParentData = firstChild!.parentData as SliverMultiBoxAdaptorParentData;
firstChildParentData.layoutOffset = layoutOffset;
return true;
}
@@ -448,15 +446,15 @@
/// during this layout pass. No child should be added during that call except
/// for the one that is created and returned by `createChild`.
@protected
- RenderBox insertAndLayoutLeadingChild(
+ RenderBox? insertAndLayoutLeadingChild(
BoxConstraints childConstraints, {
bool parentUsesSize = false,
}) {
assert(_debugAssertChildListLocked());
- final int index = indexOf(firstChild) - 1;
+ final int index = indexOf(firstChild!) - 1;
_createOrObtainChild(index, after: null);
- if (indexOf(firstChild) == index) {
- firstChild.layout(childConstraints, parentUsesSize: parentUsesSize);
+ if (indexOf(firstChild!) == index) {
+ firstChild!.layout(childConstraints, parentUsesSize: parentUsesSize);
return firstChild;
}
childManager.setDidUnderflow(true);
@@ -476,16 +474,16 @@
/// Children after the `after` child may be removed in the process. Only the
/// new child may be added.
@protected
- RenderBox insertAndLayoutChild(
+ RenderBox? insertAndLayoutChild(
BoxConstraints childConstraints, {
- @required RenderBox after,
+ required RenderBox? after,
bool parentUsesSize = false,
}) {
assert(_debugAssertChildListLocked());
assert(after != null);
- final int index = indexOf(after) + 1;
+ final int index = indexOf(after!) + 1;
_createOrObtainChild(index, after: after);
- final RenderBox child = childAfter(after);
+ final RenderBox? child = childAfter(after);
if (child != null && indexOf(child) == index) {
child.layout(childConstraints, parentUsesSize: parentUsesSize);
return child;
@@ -509,11 +507,11 @@
assert(childCount >= leadingGarbage + trailingGarbage);
invokeLayoutCallback<SliverConstraints>((SliverConstraints constraints) {
while (leadingGarbage > 0) {
- _destroyOrCacheChild(firstChild);
+ _destroyOrCacheChild(firstChild!);
leadingGarbage -= 1;
}
while (trailingGarbage > 0) {
- _destroyOrCacheChild(lastChild);
+ _destroyOrCacheChild(lastChild!);
trailingGarbage -= 1;
}
// Ask the child manager to remove the children that are no longer being
@@ -536,7 +534,7 @@
assert(child != null);
final SliverMultiBoxAdaptorParentData childParentData = child.parentData as SliverMultiBoxAdaptorParentData;
assert(childParentData.index != null);
- return childParentData.index;
+ return childParentData.index!;
}
/// Returns the dimension of the given child in the main axis, as given by the
@@ -551,12 +549,11 @@
case Axis.vertical:
return child.size.height;
}
- return null;
}
@override
- bool hitTestChildren(SliverHitTestResult result, { @required double mainAxisPosition, @required double crossAxisPosition }) {
- RenderBox child = lastChild;
+ bool hitTestChildren(SliverHitTestResult result, { required double mainAxisPosition, required double crossAxisPosition }) {
+ RenderBox? child = lastChild;
final BoxHitTestResult boxResult = BoxHitTestResult.wrap(result);
while (child != null) {
if (hitTestBoxChild(boxResult, child, mainAxisPosition: mainAxisPosition, crossAxisPosition: crossAxisPosition))
@@ -568,11 +565,11 @@
@override
double childMainAxisPosition(RenderBox child) {
- return childScrollOffset(child) - constraints.scrollOffset;
+ return childScrollOffset(child)! - constraints.scrollOffset;
}
@override
- double childScrollOffset(RenderObject child) {
+ double? childScrollOffset(RenderObject child) {
assert(child != null);
assert(child.parent == this);
final SliverMultiBoxAdaptorParentData childParentData = child.parentData as SliverMultiBoxAdaptorParentData;
@@ -604,7 +601,7 @@
case AxisDirection.up:
mainAxisUnit = const Offset(0.0, -1.0);
crossAxisUnit = const Offset(1.0, 0.0);
- originOffset = offset + Offset(0.0, geometry.paintExtent);
+ originOffset = offset + Offset(0.0, geometry!.paintExtent);
addExtent = true;
break;
case AxisDirection.right:
@@ -622,13 +619,13 @@
case AxisDirection.left:
mainAxisUnit = const Offset(-1.0, 0.0);
crossAxisUnit = const Offset(0.0, 1.0);
- originOffset = offset + Offset(geometry.paintExtent, 0.0);
+ originOffset = offset + Offset(geometry!.paintExtent, 0.0);
addExtent = true;
break;
}
assert(mainAxisUnit != null);
assert(addExtent != null);
- RenderBox child = firstChild;
+ RenderBox? child = firstChild;
while (child != null) {
final double mainAxisDelta = childMainAxisPosition(child);
final double crossAxisDelta = childCrossAxisPosition(child);
@@ -651,7 +648,7 @@
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
- properties.add(DiagnosticsNode.message(firstChild != null ? 'currently live children: ${indexOf(firstChild)} to ${indexOf(lastChild)}' : 'no children current live'));
+ properties.add(DiagnosticsNode.message(firstChild != null ? 'currently live children: ${indexOf(firstChild!)} to ${indexOf(lastChild!)}' : 'no children current live'));
}
/// Asserts that the reified child list is not empty and has a contiguous
@@ -661,8 +658,8 @@
bool debugAssertChildListIsNonEmptyAndContiguous() {
assert(() {
assert(firstChild != null);
- int index = indexOf(firstChild);
- RenderBox child = childAfter(firstChild);
+ int index = indexOf(firstChild!);
+ RenderBox? child = childAfter(firstChild!);
while (child != null) {
index += 1;
assert(indexOf(child) == index);
@@ -677,9 +674,9 @@
List<DiagnosticsNode> debugDescribeChildren() {
final List<DiagnosticsNode> children = <DiagnosticsNode>[];
if (firstChild != null) {
- RenderBox child = firstChild;
+ RenderBox? child = firstChild;
while (true) {
- final SliverMultiBoxAdaptorParentData childParentData = child.parentData as SliverMultiBoxAdaptorParentData;
+ final SliverMultiBoxAdaptorParentData childParentData = child!.parentData as SliverMultiBoxAdaptorParentData;
children.add(child.toDiagnosticsNode(name: 'child with index ${childParentData.index}'));
if (child == lastChild)
break;
@@ -689,7 +686,7 @@
if (_keepAliveBucket.isNotEmpty) {
final List<int> indices = _keepAliveBucket.keys.toList()..sort();
for (final int index in indices) {
- children.add(_keepAliveBucket[index].toDiagnosticsNode(
+ children.add(_keepAliveBucket[index]!.toDiagnosticsNode(
name: 'child with index $index (kept alive but not laid out)',
style: DiagnosticsTreeStyle.offstage,
));
diff --git a/packages/flutter/lib/src/rendering/sliver_padding.dart b/packages/flutter/lib/src/rendering/sliver_padding.dart
index 5f4e3bf..827993b 100644
--- a/packages/flutter/lib/src/rendering/sliver_padding.dart
+++ b/packages/flutter/lib/src/rendering/sliver_padding.dart
@@ -2,8 +2,6 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-// @dart = 2.8
-
import 'dart:math' as math;
import 'package:flutter/foundation.dart';
@@ -34,7 +32,7 @@
/// bottom. These values are not affected by the [TextDirection].
///
/// Must not be null or contain negative values when [performLayout] is called.
- EdgeInsets get resolvedPadding;
+ EdgeInsets? get resolvedPadding;
/// The padding in the scroll direction on the side nearest the 0.0 scroll direction.
///
@@ -47,15 +45,14 @@
assert(resolvedPadding != null);
switch (applyGrowthDirectionToAxisDirection(constraints.axisDirection, constraints.growthDirection)) {
case AxisDirection.up:
- return resolvedPadding.bottom;
+ return resolvedPadding!.bottom;
case AxisDirection.right:
- return resolvedPadding.left;
+ return resolvedPadding!.left;
case AxisDirection.down:
- return resolvedPadding.top;
+ return resolvedPadding!.top;
case AxisDirection.left:
- return resolvedPadding.right;
+ return resolvedPadding!.right;
}
- return null;
}
/// The padding in the scroll direction on the side furthest from the 0.0 scroll offset.
@@ -69,15 +66,14 @@
assert(resolvedPadding != null);
switch (applyGrowthDirectionToAxisDirection(constraints.axisDirection, constraints.growthDirection)) {
case AxisDirection.up:
- return resolvedPadding.top;
+ return resolvedPadding!.top;
case AxisDirection.right:
- return resolvedPadding.right;
+ return resolvedPadding!.right;
case AxisDirection.down:
- return resolvedPadding.bottom;
+ return resolvedPadding!.bottom;
case AxisDirection.left:
- return resolvedPadding.left;
+ return resolvedPadding!.left;
}
- return null;
}
/// The total padding in the [SliverConstraints.axisDirection]. (In other
@@ -90,7 +86,7 @@
assert(constraints != null);
assert(constraints.axis != null);
assert(resolvedPadding != null);
- return resolvedPadding.along(constraints.axis);
+ return resolvedPadding!.along(constraints.axis);
}
/// The total padding in the cross-axis direction. (In other words, for a
@@ -105,11 +101,10 @@
assert(resolvedPadding != null);
switch (constraints.axis) {
case Axis.horizontal:
- return resolvedPadding.vertical;
+ return resolvedPadding!.vertical;
case Axis.vertical:
- return resolvedPadding.horizontal;
+ return resolvedPadding!.horizontal;
}
- return null;
}
@override
@@ -134,7 +129,7 @@
);
return;
}
- child.layout(
+ child!.layout(
constraints.copyWith(
scrollOffset: math.max(0.0, constraints.scrollOffset - beforePadding),
cacheOrigin: math.min(0.0, constraints.cacheOrigin + beforePadding),
@@ -146,7 +141,7 @@
),
parentUsesSize: true,
);
- final SliverGeometry childLayoutGeometry = child.geometry;
+ final SliverGeometry childLayoutGeometry = child!.geometry!;
if (childLayoutGeometry.scrollOffsetCorrection != null) {
geometry = SliverGeometry(
scrollOffsetCorrection: childLayoutGeometry.scrollOffsetCorrection,
@@ -192,21 +187,21 @@
hasVisualOverflow: childLayoutGeometry.hasVisualOverflow,
);
- final SliverPhysicalParentData childParentData = child.parentData as SliverPhysicalParentData;
+ final SliverPhysicalParentData childParentData = child!.parentData as SliverPhysicalParentData;
assert(constraints.axisDirection != null);
assert(constraints.growthDirection != null);
switch (applyGrowthDirectionToAxisDirection(constraints.axisDirection, constraints.growthDirection)) {
case AxisDirection.up:
- childParentData.paintOffset = Offset(resolvedPadding.left, calculatePaintOffset(constraints, from: resolvedPadding.bottom + childLayoutGeometry.scrollExtent, to: resolvedPadding.bottom + childLayoutGeometry.scrollExtent + resolvedPadding.top));
+ childParentData.paintOffset = Offset(resolvedPadding!.left, calculatePaintOffset(constraints, from: resolvedPadding!.bottom + childLayoutGeometry.scrollExtent, to: resolvedPadding!.bottom + childLayoutGeometry.scrollExtent + resolvedPadding!.top));
break;
case AxisDirection.right:
- childParentData.paintOffset = Offset(calculatePaintOffset(constraints, from: 0.0, to: resolvedPadding.left), resolvedPadding.top);
+ childParentData.paintOffset = Offset(calculatePaintOffset(constraints, from: 0.0, to: resolvedPadding!.left), resolvedPadding!.top);
break;
case AxisDirection.down:
- childParentData.paintOffset = Offset(resolvedPadding.left, calculatePaintOffset(constraints, from: 0.0, to: resolvedPadding.top));
+ childParentData.paintOffset = Offset(resolvedPadding!.left, calculatePaintOffset(constraints, from: 0.0, to: resolvedPadding!.top));
break;
case AxisDirection.left:
- childParentData.paintOffset = Offset(calculatePaintOffset(constraints, from: resolvedPadding.right + childLayoutGeometry.scrollExtent, to: resolvedPadding.right + childLayoutGeometry.scrollExtent + resolvedPadding.left), resolvedPadding.top);
+ childParentData.paintOffset = Offset(calculatePaintOffset(constraints, from: resolvedPadding!.right + childLayoutGeometry.scrollExtent, to: resolvedPadding!.right + childLayoutGeometry.scrollExtent + resolvedPadding!.left), resolvedPadding!.top);
break;
}
assert(childParentData.paintOffset != null);
@@ -217,16 +212,16 @@
}
@override
- bool hitTestChildren(SliverHitTestResult result, { @required double mainAxisPosition, @required double crossAxisPosition }) {
- if (child != null && child.geometry.hitTestExtent > 0.0) {
- final SliverPhysicalParentData childParentData = child.parentData as SliverPhysicalParentData;
+ bool hitTestChildren(SliverHitTestResult result, { required double mainAxisPosition, required double crossAxisPosition }) {
+ if (child != null && child!.geometry!.hitTestExtent > 0.0) {
+ final SliverPhysicalParentData childParentData = child!.parentData as SliverPhysicalParentData;
result.addWithAxisOffset(
mainAxisPosition: mainAxisPosition,
crossAxisPosition: crossAxisPosition,
- mainAxisOffset: childMainAxisPosition(child),
- crossAxisOffset: childCrossAxisPosition(child),
+ mainAxisOffset: childMainAxisPosition(child!),
+ crossAxisOffset: childCrossAxisPosition(child!),
paintOffset: childParentData.paintOffset,
- hitTest: child.hitTest,
+ hitTest: child!.hitTest,
);
}
return false;
@@ -250,16 +245,15 @@
switch (applyGrowthDirectionToAxisDirection(constraints.axisDirection, constraints.growthDirection)) {
case AxisDirection.up:
case AxisDirection.down:
- return resolvedPadding.left;
+ return resolvedPadding!.left;
case AxisDirection.left:
case AxisDirection.right:
- return resolvedPadding.top;
+ return resolvedPadding!.top;
}
- return null;
}
@override
- double childScrollOffset(RenderObject child) {
+ double? childScrollOffset(RenderObject child) {
assert(child.parent == this);
return beforePadding;
}
@@ -274,9 +268,9 @@
@override
void paint(PaintingContext context, Offset offset) {
- if (child != null && child.geometry.visible) {
- final SliverPhysicalParentData childParentData = child.parentData as SliverPhysicalParentData;
- context.paintChild(child, offset + childParentData.paintOffset);
+ if (child != null && child!.geometry!.visible) {
+ final SliverPhysicalParentData childParentData = child!.parentData as SliverPhysicalParentData;
+ context.paintChild(child!, offset + childParentData.paintOffset);
}
}
@@ -288,10 +282,10 @@
final Size parentSize = getAbsoluteSize();
final Rect outerRect = offset & parentSize;
Size childSize;
- Rect innerRect;
+ Rect? innerRect;
if (child != null) {
- childSize = child.getAbsoluteSize();
- final SliverPhysicalParentData childParentData = child.parentData as SliverPhysicalParentData;
+ childSize = child!.getAbsoluteSize();
+ final SliverPhysicalParentData childParentData = child!.parentData as SliverPhysicalParentData;
innerRect = (offset + childParentData.paintOffset) & childSize;
assert(innerRect.top >= outerRect.top);
assert(innerRect.left >= outerRect.left);
@@ -317,9 +311,9 @@
///
/// The [padding] argument must not be null and must have non-negative insets.
RenderSliverPadding({
- @required EdgeInsetsGeometry padding,
- TextDirection textDirection,
- RenderSliver child,
+ required EdgeInsetsGeometry padding,
+ TextDirection? textDirection,
+ RenderSliver? child,
}) : assert(padding != null),
assert(padding.isNonNegative),
_padding = padding,
@@ -328,14 +322,14 @@
}
@override
- EdgeInsets get resolvedPadding => _resolvedPadding;
- EdgeInsets _resolvedPadding;
+ EdgeInsets? get resolvedPadding => _resolvedPadding;
+ EdgeInsets? _resolvedPadding;
void _resolve() {
if (resolvedPadding != null)
return;
_resolvedPadding = padding.resolve(textDirection);
- assert(resolvedPadding.isNonNegative);
+ assert(resolvedPadding!.isNonNegative);
}
void _markNeedsResolution() {
@@ -362,9 +356,9 @@
///
/// This may be changed to null, but only after the [padding] has been changed
/// to a value that does not depend on the direction.
- TextDirection get textDirection => _textDirection;
- TextDirection _textDirection;
- set textDirection(TextDirection value) {
+ TextDirection? get textDirection => _textDirection;
+ TextDirection? _textDirection;
+ set textDirection(TextDirection? value) {
if (_textDirection == value)
return;
_textDirection = value;
diff --git a/packages/flutter/lib/src/rendering/sliver_persistent_header.dart b/packages/flutter/lib/src/rendering/sliver_persistent_header.dart
index b88c7d6..54d9348 100644
--- a/packages/flutter/lib/src/rendering/sliver_persistent_header.dart
+++ b/packages/flutter/lib/src/rendering/sliver_persistent_header.dart
@@ -2,8 +2,6 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-// @dart = 2.8
-
import 'dart:math' as math;
import 'package:flutter/animation.dart';
@@ -38,7 +36,7 @@
/// The callback function to be executed when a user over-scrolls to the
/// offset specified by [stretchTriggerOffset].
- final AsyncCallback onStretchTrigger;
+ final AsyncCallback? onStretchTrigger;
}
/// A base class for slivers that have a [RenderBox] child which scrolls
@@ -63,13 +61,13 @@
///
/// This is an abstract class; this constructor only initializes the [child].
RenderSliverPersistentHeader({
- RenderBox child,
+ RenderBox? child,
this.stretchConfiguration,
}) {
this.child = child;
}
- double _lastStretchOffset;
+ late double _lastStretchOffset;
/// The biggest that this render object can become, in the main axis direction.
///
@@ -90,15 +88,14 @@
double get childExtent {
if (child == null)
return 0.0;
- assert(child.hasSize);
+ assert(child!.hasSize);
assert(constraints.axis != null);
switch (constraints.axis) {
case Axis.vertical:
- return child.size.height;
+ return child!.size.height;
case Axis.horizontal:
- return child.size.width;
+ return child!.size.width;
}
- return null;
}
bool _needsUpdateChild = true;
@@ -114,7 +111,7 @@
///
/// * [SliverAppBar], which creates a header that can stretched into an
/// overscroll area and trigger a callback function.
- OverScrollHeaderStretchConfiguration stretchConfiguration;
+ OverScrollHeaderStretchConfiguration? stretchConfiguration;
/// Update the child render object if necessary.
///
@@ -179,8 +176,9 @@
]);
}());
double stretchOffset = 0.0;
- if (stretchConfiguration != null && childMainAxisPosition(child) == 0.0)
+ if (stretchConfiguration != null && constraints.scrollOffset == 0.0) {
stretchOffset += constraints.overlap.abs();
+ }
child?.layout(
constraints.asBoxConstraints(
@@ -190,10 +188,10 @@
);
if (stretchConfiguration != null &&
- stretchConfiguration.onStretchTrigger != null &&
- stretchOffset >= stretchConfiguration.stretchTriggerOffset &&
- _lastStretchOffset <= stretchConfiguration.stretchTriggerOffset) {
- stretchConfiguration.onStretchTrigger();
+ stretchConfiguration!.onStretchTrigger != null &&
+ stretchOffset >= stretchConfiguration!.stretchTriggerOffset &&
+ _lastStretchOffset <= stretchConfiguration!.stretchTriggerOffset) {
+ stretchConfiguration!.onStretchTrigger!();
}
_lastStretchOffset = stretchOffset;
}
@@ -222,10 +220,10 @@
double childMainAxisPosition(covariant RenderObject child) => super.childMainAxisPosition(child);
@override
- bool hitTestChildren(SliverHitTestResult result, { @required double mainAxisPosition, @required double crossAxisPosition }) {
- assert(geometry.hitTestExtent > 0.0);
+ bool hitTestChildren(SliverHitTestResult result, { required double mainAxisPosition, required double crossAxisPosition }) {
+ assert(geometry!.hitTestExtent > 0.0);
if (child != null)
- return hitTestBoxChild(BoxHitTestResult.wrap(result), child, mainAxisPosition: mainAxisPosition, crossAxisPosition: crossAxisPosition);
+ return hitTestBoxChild(BoxHitTestResult.wrap(result), child!, mainAxisPosition: mainAxisPosition, crossAxisPosition: crossAxisPosition);
return false;
}
@@ -238,23 +236,23 @@
@override
void paint(PaintingContext context, Offset offset) {
- if (child != null && geometry.visible) {
+ if (child != null && geometry!.visible) {
assert(constraints.axisDirection != null);
switch (applyGrowthDirectionToAxisDirection(constraints.axisDirection, constraints.growthDirection)) {
case AxisDirection.up:
- offset += Offset(0.0, geometry.paintExtent - childMainAxisPosition(child) - childExtent);
+ offset += Offset(0.0, geometry!.paintExtent - childMainAxisPosition(child!) - childExtent);
break;
case AxisDirection.down:
- offset += Offset(0.0, childMainAxisPosition(child));
+ offset += Offset(0.0, childMainAxisPosition(child!));
break;
case AxisDirection.left:
- offset += Offset(geometry.paintExtent - childMainAxisPosition(child) - childExtent, 0.0);
+ offset += Offset(geometry!.paintExtent - childMainAxisPosition(child!) - childExtent, 0.0);
break;
case AxisDirection.right:
- offset += Offset(childMainAxisPosition(child), 0.0);
+ offset += Offset(childMainAxisPosition(child!), 0.0);
break;
}
- context.paintChild(child, offset);
+ context.paintChild(child!, offset);
}
}
@@ -268,7 +266,7 @@
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DoubleProperty.lazy('maxExtent', () => maxExtent));
- properties.add(DoubleProperty.lazy('child position', () => childMainAxisPosition(child)));
+ properties.add(DoubleProperty.lazy('child position', () => childMainAxisPosition(child!)));
}
}
@@ -281,8 +279,8 @@
/// Creates a sliver that shrinks when it hits the start of the viewport, then
/// scrolls off.
RenderSliverScrollingPersistentHeader({
- RenderBox child,
- OverScrollHeaderStretchConfiguration stretchConfiguration,
+ RenderBox? child,
+ OverScrollHeaderStretchConfiguration? stretchConfiguration,
}) : super(
child: child,
stretchConfiguration: stretchConfiguration,
@@ -290,7 +288,7 @@
// Distance from our leading edge to the child's leading edge, in the axis
// direction. Negative if we're scrolled off the top.
- double _childPosition;
+ double? _childPosition;
/// Updates [geometry], and returns the new value for [childMainAxisPosition].
///
@@ -306,7 +304,7 @@
geometry = SliverGeometry(
scrollExtent: maxExtent,
paintOrigin: math.min(constraints.overlap, 0.0),
- paintExtent: paintExtent.clamp(0.0, constraints.remainingPaintExtent) as double,
+ paintExtent: paintExtent.clamp(0.0, constraints.remainingPaintExtent),
maxPaintExtent: maxExtent + stretchOffset,
hasVisualOverflow: true, // Conservatively say we do have overflow to avoid complexity.
);
@@ -323,7 +321,7 @@
geometry = SliverGeometry(
scrollExtent: maxExtent,
paintOrigin: math.min(constraints.overlap, 0.0),
- paintExtent: paintExtent.clamp(0.0, constraints.remainingPaintExtent) as double,
+ paintExtent: paintExtent.clamp(0.0, constraints.remainingPaintExtent),
maxPaintExtent: maxExtent,
hasVisualOverflow: true, // Conservatively say we do have overflow to avoid complexity.
);
@@ -333,7 +331,8 @@
@override
double childMainAxisPosition(RenderBox child) {
assert(child == this.child);
- return _childPosition;
+ assert(_childPosition != null);
+ return _childPosition!;
}
}
@@ -346,8 +345,8 @@
/// Creates a sliver that shrinks when it hits the start of the viewport, then
/// stays pinned there.
RenderSliverPinnedPersistentHeader({
- RenderBox child,
- OverScrollHeaderStretchConfiguration stretchConfiguration,
+ RenderBox? child,
+ OverScrollHeaderStretchConfiguration? stretchConfiguration,
}) : super(
child: child,
stretchConfiguration: stretchConfiguration,
@@ -360,7 +359,7 @@
final bool overlapsContent = constraints.overlap > 0.0;
layoutChild(constraints.scrollOffset, maxExtent, overlapsContent: overlapsContent);
final double effectiveRemainingPaintExtent = math.max(0, constraints.remainingPaintExtent - constraints.overlap);
- final double layoutExtent = (maxExtent - constraints.scrollOffset).clamp(0.0, effectiveRemainingPaintExtent) as double;
+ final double layoutExtent = (maxExtent - constraints.scrollOffset).clamp(0.0, effectiveRemainingPaintExtent);
final double stretchOffset = stretchConfiguration != null ?
constraints.overlap.abs() :
0.0;
@@ -394,7 +393,7 @@
/// Creates an object that specifies how a floating header is to be "snapped"
/// (animated) into or out of view.
FloatingHeaderSnapConfiguration({
- @required this.vsync,
+ required this.vsync,
this.curve = Curves.ease,
this.duration = const Duration(milliseconds: 300),
}) : assert(vsync != null),
@@ -425,23 +424,23 @@
/// scrolls off, and comes back immediately when the user reverses the scroll
/// direction.
RenderSliverFloatingPersistentHeader({
- RenderBox child,
- FloatingHeaderSnapConfiguration snapConfiguration,
- OverScrollHeaderStretchConfiguration stretchConfiguration,
+ RenderBox? child,
+ FloatingHeaderSnapConfiguration? snapConfiguration,
+ OverScrollHeaderStretchConfiguration? stretchConfiguration,
}) : _snapConfiguration = snapConfiguration,
super(
child: child,
stretchConfiguration: stretchConfiguration,
);
- AnimationController _controller;
- Animation<double> _animation;
- double _lastActualScrollOffset;
- double _effectiveScrollOffset;
+ AnimationController? _controller;
+ late Animation<double> _animation;
+ double? _lastActualScrollOffset;
+ double? _effectiveScrollOffset;
// Distance from our leading edge to the child's leading edge, in the axis
// direction. Negative if we're scrolled off the top.
- double _childPosition;
+ double? _childPosition;
@override
void detach() {
@@ -462,16 +461,16 @@
/// start or stop the floating header's animation.
/// * [SliverAppBar], which creates a header that can be pinned, floating,
/// and snapped into view via the corresponding parameters.
- FloatingHeaderSnapConfiguration get snapConfiguration => _snapConfiguration;
- FloatingHeaderSnapConfiguration _snapConfiguration;
- set snapConfiguration(FloatingHeaderSnapConfiguration value) {
+ FloatingHeaderSnapConfiguration? get snapConfiguration => _snapConfiguration;
+ FloatingHeaderSnapConfiguration? _snapConfiguration;
+ set snapConfiguration(FloatingHeaderSnapConfiguration? value) {
if (value == _snapConfiguration)
return;
if (value == null) {
_controller?.dispose();
_controller = null;
} else {
- if (_snapConfiguration != null && value.vsync != _snapConfiguration.vsync)
+ if (_snapConfiguration != null && value.vsync != _snapConfiguration!.vsync)
_controller?.resync(value.vsync);
}
_snapConfiguration = value;
@@ -487,13 +486,13 @@
stretchOffset += constraints.overlap.abs();
}
final double maxExtent = this.maxExtent;
- final double paintExtent = maxExtent - _effectiveScrollOffset;
+ final double paintExtent = maxExtent - _effectiveScrollOffset!;
final double layoutExtent = maxExtent - constraints.scrollOffset;
geometry = SliverGeometry(
scrollExtent: maxExtent,
paintOrigin: math.min(constraints.overlap, 0.0),
- paintExtent: paintExtent.clamp(0.0, constraints.remainingPaintExtent) as double,
- layoutExtent: layoutExtent.clamp(0.0, constraints.remainingPaintExtent) as double,
+ paintExtent: paintExtent.clamp(0.0, constraints.remainingPaintExtent),
+ layoutExtent: layoutExtent.clamp(0.0, constraints.remainingPaintExtent),
maxPaintExtent: maxExtent + stretchOffset,
hasVisualOverflow: true, // Conservatively say we do have overflow to avoid complexity.
);
@@ -504,13 +503,13 @@
void maybeStartSnapAnimation(ScrollDirection direction) {
if (snapConfiguration == null)
return;
- if (direction == ScrollDirection.forward && _effectiveScrollOffset <= 0.0)
+ if (direction == ScrollDirection.forward && _effectiveScrollOffset! <= 0.0)
return;
- if (direction == ScrollDirection.reverse && _effectiveScrollOffset >= maxExtent)
+ if (direction == ScrollDirection.reverse && _effectiveScrollOffset! >= maxExtent)
return;
- final TickerProvider vsync = snapConfiguration.vsync;
- final Duration duration = snapConfiguration.duration;
+ final TickerProvider vsync = snapConfiguration!.vsync;
+ final Duration duration = snapConfiguration!.duration;
_controller ??= AnimationController(vsync: vsync, duration: duration)
..addListener(() {
if (_effectiveScrollOffset == _animation.value)
@@ -519,16 +518,16 @@
markNeedsLayout();
});
- _animation = _controller.drive(
+ _animation = _controller!.drive(
Tween<double>(
begin: _effectiveScrollOffset,
end: direction == ScrollDirection.forward ? 0.0 : maxExtent,
).chain(CurveTween(
- curve: snapConfiguration.curve,
+ curve: snapConfiguration!.curve,
)),
);
- _controller.forward(from: 0.0);
+ _controller!.forward(from: 0.0);
}
/// If a header snap animation is underway then stop it.
@@ -541,26 +540,26 @@
final SliverConstraints constraints = this.constraints;
final double maxExtent = this.maxExtent;
if (_lastActualScrollOffset != null && // We've laid out at least once to get an initial position, and either
- ((constraints.scrollOffset < _lastActualScrollOffset) || // we are scrolling back, so should reveal, or
- (_effectiveScrollOffset < maxExtent))) { // some part of it is visible, so should shrink or reveal as appropriate.
- double delta = _lastActualScrollOffset - constraints.scrollOffset;
+ ((constraints.scrollOffset < _lastActualScrollOffset!) || // we are scrolling back, so should reveal, or
+ (_effectiveScrollOffset! < maxExtent))) { // some part of it is visible, so should shrink or reveal as appropriate.
+ double delta = _lastActualScrollOffset! - constraints.scrollOffset;
final bool allowFloatingExpansion = constraints.userScrollDirection == ScrollDirection.forward;
if (allowFloatingExpansion) {
- if (_effectiveScrollOffset > maxExtent) // We're scrolled off-screen, but should reveal, so
+ if (_effectiveScrollOffset! > maxExtent) // We're scrolled off-screen, but should reveal, so
_effectiveScrollOffset = maxExtent; // pretend we're just at the limit.
} else {
if (delta > 0.0) // If we are trying to expand when allowFloatingExpansion is false,
delta = 0.0; // disallow the expansion. (But allow shrinking, i.e. delta < 0.0 is fine.)
}
- _effectiveScrollOffset = (_effectiveScrollOffset - delta).clamp(0.0, constraints.scrollOffset) as double;
+ _effectiveScrollOffset = (_effectiveScrollOffset! - delta).clamp(0.0, constraints.scrollOffset);
} else {
_effectiveScrollOffset = constraints.scrollOffset;
}
- final bool overlapsContent = _effectiveScrollOffset < constraints.scrollOffset;
+ final bool overlapsContent = _effectiveScrollOffset! < constraints.scrollOffset;
layoutChild(
- _effectiveScrollOffset,
+ _effectiveScrollOffset!,
maxExtent,
overlapsContent: overlapsContent,
);
@@ -571,7 +570,7 @@
@override
double childMainAxisPosition(RenderBox child) {
assert(child == this.child);
- return _childPosition;
+ return _childPosition ?? 0.0;
}
@override
@@ -594,9 +593,9 @@
/// stays pinned there, and grows immediately when the user reverses the
/// scroll direction.
RenderSliverFloatingPinnedPersistentHeader({
- RenderBox child,
- FloatingHeaderSnapConfiguration snapConfiguration,
- OverScrollHeaderStretchConfiguration stretchConfiguration,
+ RenderBox? child,
+ FloatingHeaderSnapConfiguration? snapConfiguration,
+ OverScrollHeaderStretchConfiguration? stretchConfiguration,
}) : super(
child: child,
snapConfiguration: snapConfiguration,
@@ -610,11 +609,11 @@
minExtent :
constraints.remainingPaintExtent;
final double maxExtent = this.maxExtent;
- final double paintExtent = maxExtent - _effectiveScrollOffset;
+ final double paintExtent = maxExtent - _effectiveScrollOffset!;
final double clampedPaintExtent = paintExtent.clamp(
minAllowedExtent,
constraints.remainingPaintExtent,
- ) as double;
+ );
final double layoutExtent = maxExtent - constraints.scrollOffset;
final double stretchOffset = stretchConfiguration != null ?
constraints.overlap.abs() :
@@ -623,7 +622,7 @@
scrollExtent: maxExtent,
paintOrigin: math.min(constraints.overlap, 0.0),
paintExtent: clampedPaintExtent,
- layoutExtent: layoutExtent.clamp(0.0, clampedPaintExtent) as double,
+ layoutExtent: layoutExtent.clamp(0.0, clampedPaintExtent),
maxPaintExtent: maxExtent + stretchOffset,
maxScrollObstructionExtent: minExtent,
hasVisualOverflow: true, // Conservatively say we do have overflow to avoid complexity.
diff --git a/packages/flutter/lib/src/rendering/stack.dart b/packages/flutter/lib/src/rendering/stack.dart
index b6e7d74..3f27f4e 100644
--- a/packages/flutter/lib/src/rendering/stack.dart
+++ b/packages/flutter/lib/src/rendering/stack.dart
@@ -2,8 +2,6 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-// @dart = 2.8
-
import 'dart:math' as math;
import 'dart:ui' show lerpDouble, hashValues;
@@ -62,22 +60,22 @@
/// Distance from the left side of the container to the left side of this rectangle.
///
/// May be negative if the left side of the rectangle is outside of the container.
- final double/*!*/ left;
+ final double left;
/// Distance from the top side of the container to the top side of this rectangle.
///
/// May be negative if the top side of the rectangle is outside of the container.
- final double/*!*/ top;
+ final double top;
/// Distance from the right side of the container to the right side of this rectangle.
///
/// May be positive if the right side of the rectangle is outside of the container.
- final double/*!*/ right;
+ final double right;
/// Distance from the bottom side of the container to the bottom side of this rectangle.
///
/// May be positive if the bottom side of the rectangle is outside of the container.
- final double/*!*/ bottom;
+ final double bottom;
/// Returns whether any of the values are greater than zero.
///
@@ -134,21 +132,21 @@
/// If either rect is null, this function interpolates from [RelativeRect.fill].
///
/// {@macro dart.ui.shadow.lerp}
- static RelativeRect lerp(RelativeRect/*?*/ a, RelativeRect/*?*/ b, double t) {
+ static RelativeRect? lerp(RelativeRect? a, RelativeRect? b, double t) {
assert(t != null);
if (a == null && b == null)
return null;
if (a == null)
- return RelativeRect.fromLTRB(b.left * t, b.top * t, b.right * t, b.bottom * t);
+ return RelativeRect.fromLTRB(b!.left * t, b.top * t, b.right * t, b.bottom * t);
if (b == null) {
final double k = 1.0 - t;
- return RelativeRect.fromLTRB(b.left * k, b.top * k, b.right * k, b.bottom * k);
+ return RelativeRect.fromLTRB(b!.left * k, b.top * k, b.right * k, b.bottom * k);
}
return RelativeRect.fromLTRB(
- lerpDouble(a.left, b.left, t),
- lerpDouble(a.top, b.top, t),
- lerpDouble(a.right, b.right, t),
- lerpDouble(a.bottom, b.bottom, t),
+ lerpDouble(a.left, b.left, t)!,
+ lerpDouble(a.top, b.top, t)!,
+ lerpDouble(a.right, b.right, t)!,
+ lerpDouble(a.bottom, b.bottom, t)!,
);
}
@@ -167,35 +165,35 @@
int get hashCode => hashValues(left, top, right, bottom);
@override
- String toString() => 'RelativeRect.fromLTRB(${left?.toStringAsFixed(1)}, ${top?.toStringAsFixed(1)}, ${right?.toStringAsFixed(1)}, ${bottom?.toStringAsFixed(1)})';
+ String toString() => 'RelativeRect.fromLTRB(${left.toStringAsFixed(1)}, ${top.toStringAsFixed(1)}, ${right.toStringAsFixed(1)}, ${bottom.toStringAsFixed(1)})';
}
/// Parent data for use with [RenderStack].
class StackParentData extends ContainerBoxParentData<RenderBox> {
/// The distance by which the child's top edge is inset from the top of the stack.
- double top;
+ double? top;
/// The distance by which the child's right edge is inset from the right of the stack.
- double right;
+ double? right;
/// The distance by which the child's bottom edge is inset from the bottom of the stack.
- double bottom;
+ double? bottom;
/// The distance by which the child's left edge is inset from the left of the stack.
- double left;
+ double? left;
/// The child's width.
///
/// Ignored if both left and right are non-null.
- double width;
+ double? width;
/// The child's height.
///
/// Ignored if both top and bottom are non-null.
- double height;
+ double? height;
/// Get or set the current values in terms of a RelativeRect object.
- RelativeRect get rect => RelativeRect.fromLTRB(left, top, right, bottom);
+ RelativeRect get rect => RelativeRect.fromLTRB(left!, top!, right!, bottom!);
set rect(RelativeRect value) {
top = value.top;
right = value.right;
@@ -328,9 +326,9 @@
/// By default, the non-positioned children of the stack are aligned by their
/// top left corners.
RenderStack({
- List<RenderBox> children,
+ List<RenderBox>? children,
AlignmentGeometry alignment = AlignmentDirectional.topStart,
- TextDirection textDirection,
+ TextDirection? textDirection,
StackFit fit = StackFit.loose,
Clip clipBehavior = Clip.hardEdge,
}) : assert(alignment != null),
@@ -351,7 +349,7 @@
child.parentData = StackParentData();
}
- Alignment _resolvedAlignment;
+ Alignment? _resolvedAlignment;
void _resolve() {
if (_resolvedAlignment != null)
@@ -393,9 +391,9 @@
///
/// This may be changed to null, but only after the [alignment] has been changed
/// to a value that does not depend on the direction.
- TextDirection get textDirection => _textDirection;
- TextDirection _textDirection;
- set textDirection(TextDirection value) {
+ TextDirection? get textDirection => _textDirection;
+ TextDirection? _textDirection;
+ set textDirection(TextDirection? value) {
if (_textDirection == value)
return;
_textDirection = value;
@@ -432,9 +430,9 @@
}
/// Helper function for calculating the intrinsics metrics of a Stack.
- static double getIntrinsicDimension(RenderBox firstChild, double mainChildSizeGetter(RenderBox child)) {
+ static double getIntrinsicDimension(RenderBox? firstChild, double mainChildSizeGetter(RenderBox child)) {
double extent = 0.0;
- RenderBox child = firstChild;
+ RenderBox? child = firstChild;
while (child != null) {
final StackParentData childParentData = child.parentData as StackParentData;
if (!childParentData.isPositioned)
@@ -466,7 +464,7 @@
}
@override
- double computeDistanceToActualBaseline(TextBaseline baseline) {
+ double? computeDistanceToActualBaseline(TextBaseline baseline) {
return defaultComputeDistanceToHighestActualBaseline(baseline);
}
@@ -481,23 +479,22 @@
BoxConstraints childConstraints = const BoxConstraints();
if (childParentData.left != null && childParentData.right != null)
- childConstraints = childConstraints.tighten(width: size.width - childParentData.right - childParentData.left);
+ childConstraints = childConstraints.tighten(width: size.width - childParentData.right! - childParentData.left!);
else if (childParentData.width != null)
childConstraints = childConstraints.tighten(width: childParentData.width);
if (childParentData.top != null && childParentData.bottom != null)
- childConstraints = childConstraints.tighten(height: size.height - childParentData.bottom - childParentData.top);
+ childConstraints = childConstraints.tighten(height: size.height - childParentData.bottom! - childParentData.top!);
else if (childParentData.height != null)
childConstraints = childConstraints.tighten(height: childParentData.height);
child.layout(childConstraints, parentUsesSize: true);
- // TODO(ianh): x should be late final
- /*late*/ double/*!*/ x;
+ late final double x;
if (childParentData.left != null) {
- x = childParentData.left;
+ x = childParentData.left!;
} else if (childParentData.right != null) {
- x = size.width - childParentData.right - child.size.width;
+ x = size.width - childParentData.right! - child.size.width;
} else {
x = alignment.alongOffset(size - child.size as Offset).dx;
}
@@ -505,12 +502,11 @@
if (x < 0.0 || x + child.size.width > size.width)
hasVisualOverflow = true;
- // TODO(ianh): y should be late final
- /*late*/ double/*!*/ y;
+ late final double y;
if (childParentData.top != null) {
- y = childParentData.top;
+ y = childParentData.top!;
} else if (childParentData.bottom != null) {
- y = size.height - childParentData.bottom - child.size.height;
+ y = size.height - childParentData.bottom! - child.size.height;
} else {
y = alignment.alongOffset(size - child.size as Offset).dy;
}
@@ -554,7 +550,7 @@
}
assert(nonPositionedConstraints != null);
- RenderBox child = firstChild;
+ RenderBox? child = firstChild;
while (child != null) {
final StackParentData childParentData = child.parentData as StackParentData;
@@ -586,9 +582,9 @@
final StackParentData childParentData = child.parentData as StackParentData;
if (!childParentData.isPositioned) {
- childParentData.offset = _resolvedAlignment.alongOffset(size - child.size as Offset);
+ childParentData.offset = _resolvedAlignment!.alongOffset(size - child.size as Offset);
} else {
- _hasVisualOverflow = layoutPositionedChild(child, childParentData, size, _resolvedAlignment) || _hasVisualOverflow;
+ _hasVisualOverflow = layoutPositionedChild(child, childParentData, size, _resolvedAlignment!) || _hasVisualOverflow;
}
assert(child.parentData == childParentData);
@@ -597,7 +593,7 @@
}
@override
- bool hitTestChildren(BoxHitTestResult result, { Offset position }) {
+ bool hitTestChildren(BoxHitTestResult result, { required Offset position }) {
return defaultHitTestChildren(result, position: position);
}
@@ -620,7 +616,7 @@
}
@override
- Rect describeApproximatePaintClip(RenderObject child) => _hasVisualOverflow ? Offset.zero & size : null;
+ Rect? describeApproximatePaintClip(RenderObject child) => _hasVisualOverflow ? Offset.zero & size : null;
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
@@ -642,10 +638,10 @@
///
/// If the [index] parameter is null, nothing is displayed.
RenderIndexedStack({
- List<RenderBox> children,
+ List<RenderBox>? children,
AlignmentGeometry alignment = AlignmentDirectional.topStart,
- TextDirection textDirection,
- int index = 0,
+ TextDirection? textDirection,
+ int? index = 0,
}) : _index = index,
super(
children: children,
@@ -660,9 +656,9 @@
}
/// The index of the child to show, null if nothing is to be displayed.
- int get index => _index;
- int _index;
- set index(int value) {
+ int? get index => _index;
+ int? _index;
+ set index(int? value) {
if (_index != value) {
_index = value;
markNeedsLayout();
@@ -671,20 +667,20 @@
RenderBox _childAtIndex() {
assert(index != null);
- RenderBox child = firstChild;
+ RenderBox? child = firstChild;
int i = 0;
- while (child != null && i < index) {
+ while (child != null && i < index!) {
final StackParentData childParentData = child.parentData as StackParentData;
child = childParentData.nextSibling;
i += 1;
}
assert(i == index);
assert(child != null);
- return child;
+ return child!;
}
@override
- bool hitTestChildren(BoxHitTestResult result, { @required Offset position }) {
+ bool hitTestChildren(BoxHitTestResult result, { required Offset position }) {
if (firstChild == null || index == null)
return false;
assert(position != null);
@@ -693,9 +689,9 @@
return result.addWithPaintOffset(
offset: childParentData.offset,
position: position,
- hitTest: (BoxHitTestResult result, Offset transformed) {
+ hitTest: (BoxHitTestResult result, Offset? transformed) {
assert(transformed == position - childParentData.offset);
- return child.hitTest(result, position: transformed);
+ return child.hitTest(result, position: transformed!);
},
);
}
diff --git a/packages/flutter/lib/src/rendering/table.dart b/packages/flutter/lib/src/rendering/table.dart
index 0de906e..d0e061d 100644
--- a/packages/flutter/lib/src/rendering/table.dart
+++ b/packages/flutter/lib/src/rendering/table.dart
@@ -2,8 +2,6 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-// @dart = 2.8
-
import 'dart:collection';
import 'dart:math' as math;
@@ -16,13 +14,13 @@
/// Parent data used by [RenderTable] for its children.
class TableCellParentData extends BoxParentData {
/// Where this cell should be placed vertically.
- TableCellVerticalAlignment verticalAlignment;
+ TableCellVerticalAlignment? verticalAlignment;
/// The column that the child was in the last time it was laid out.
- int x;
+ int? x;
/// The row that the child was in the last time it was laid out.
- int y;
+ int? y;
@override
String toString() => '${super.toString()}; ${verticalAlignment == null ? "default vertical alignment" : "$verticalAlignment"}';
@@ -75,7 +73,7 @@
/// The `cells` argument is an iterable that provides all the cells
/// in the table for this column. Walking the cells is by definition
/// O(N), so algorithms that do that should be considered expensive.
- double flex(Iterable<RenderBox> cells) => null;
+ double? flex(Iterable<RenderBox> cells) => null;
@override
String toString() => objectRuntimeType(this, 'TableColumnWidth');
@@ -98,7 +96,7 @@
/// there is any room left over when laying out the table. If `flex` is
/// null (the default), the table will not distribute any extra space to the
/// column.
- const IntrinsicColumnWidth({ double flex }) : _flex = flex;
+ const IntrinsicColumnWidth({ double? flex }) : _flex = flex;
@override
double minIntrinsicWidth(Iterable<RenderBox> cells, double containerWidth) {
@@ -116,10 +114,10 @@
return result;
}
- final double _flex;
+ final double? _flex;
@override
- double flex(Iterable<RenderBox> cells) => _flex;
+ double? flex(Iterable<RenderBox> cells) => _flex;
@override
String toString() => '${objectRuntimeType(this, 'IntrinsicColumnWidth')}(flex: ${_flex?.toStringAsFixed(1)})';
@@ -257,11 +255,11 @@
}
@override
- double flex(Iterable<RenderBox> cells) {
- final double aFlex = a.flex(cells);
+ double? flex(Iterable<RenderBox> cells) {
+ final double? aFlex = a.flex(cells);
if (aFlex == null)
return b.flex(cells);
- final double bFlex = b.flex(cells);
+ final double? bFlex = b.flex(cells);
if (bFlex == null)
return null;
return math.max(aFlex, bFlex);
@@ -308,11 +306,11 @@
}
@override
- double flex(Iterable<RenderBox> cells) {
- final double aFlex = a.flex(cells);
+ double? flex(Iterable<RenderBox> cells) {
+ final double? aFlex = a.flex(cells);
if (aFlex == null)
return b.flex(cells);
- final double bFlex = b.flex(cells);
+ final double? bFlex = b.flex(cells);
if (bFlex == null)
return null;
return math.min(aFlex, bFlex);
@@ -362,43 +360,44 @@
/// null, then `children` must be null.
/// * `children` must either be null or contain lists of all the same length.
/// if `children` is not null, then `rows` must be null.
+ /// * [columnWidths] may be null, in which case it defaults to an empty map.
/// * [defaultColumnWidth] must not be null.
/// * [configuration] must not be null (but has a default value).
RenderTable({
- int columns,
- int rows,
- Map<int, TableColumnWidth> columnWidths,
+ int? columns,
+ int? rows,
+ Map<int, TableColumnWidth>? columnWidths,
TableColumnWidth defaultColumnWidth = const FlexColumnWidth(1.0),
- @required TextDirection textDirection,
- TableBorder border,
- List<Decoration> rowDecorations,
+ required TextDirection textDirection,
+ TableBorder? border,
+ List<Decoration?>? rowDecorations,
ImageConfiguration configuration = ImageConfiguration.empty,
TableCellVerticalAlignment defaultVerticalAlignment = TableCellVerticalAlignment.top,
- TextBaseline textBaseline,
- List<List<RenderBox>> children,
+ TextBaseline? textBaseline,
+ List<List<RenderBox>>? children,
}) : assert(columns == null || columns >= 0),
assert(rows == null || rows >= 0),
assert(rows == null || children == null),
assert(defaultColumnWidth != null),
assert(textDirection != null),
assert(configuration != null),
- _textDirection = textDirection {
- _columns = columns ?? (children != null && children.isNotEmpty ? children.first.length : 0);
- _rows = rows ?? 0;
+ _textDirection = textDirection,
+ _columns = columns ?? (children != null && children.isNotEmpty ? children.first.length : 0),
+ _rows = rows ?? 0,
+ _columnWidths = columnWidths ?? HashMap<int, TableColumnWidth>(),
+ _defaultColumnWidth = defaultColumnWidth,
+ _border = border,
+ _textBaseline = textBaseline,
+ _defaultVerticalAlignment = defaultVerticalAlignment,
+ _configuration = configuration {
_children = <RenderBox>[]..length = _columns * _rows;
- _columnWidths = columnWidths ?? HashMap<int, TableColumnWidth>();
- _defaultColumnWidth = defaultColumnWidth;
- _border = border;
this.rowDecorations = rowDecorations; // must use setter to initialize box painters array
- _configuration = configuration;
- _defaultVerticalAlignment = defaultVerticalAlignment;
- _textBaseline = textBaseline;
children?.forEach(addRow);
}
// Children are stored in row-major order.
// _children.length must be rows * columns
- List<RenderBox> _children = const <RenderBox>[];
+ List<RenderBox?> _children = const <RenderBox?>[];
/// The number of vertical alignment lines in this table.
///
@@ -415,9 +414,9 @@
if (value == columns)
return;
final int oldColumns = columns;
- final List<RenderBox> oldChildren = _children;
+ final List<RenderBox?> oldChildren = _children;
_columns = value;
- _children = <RenderBox>[]..length = columns * rows;
+ _children = List<RenderBox?>.filled(columns * rows, null, growable: false);
final int columnsToCopy = math.min(columns, oldColumns);
for (int y = 0; y < rows; y += 1) {
for (int x = 0; x < columnsToCopy; x += 1)
@@ -428,7 +427,7 @@
for (int x = columns; x < oldColumns; x += 1) {
final int xy = x + y * oldColumns;
if (oldChildren[xy] != null)
- dropChild(oldChildren[xy]);
+ dropChild(oldChildren[xy]!);
}
}
}
@@ -449,7 +448,7 @@
if (_rows > value) {
for (int xy = columns * value; xy < _children.length; xy += 1) {
if (_children[xy] != null)
- dropChild(_children[xy]);
+ dropChild(_children[xy]!);
}
}
_rows = value;
@@ -466,13 +465,18 @@
/// sizing algorithms are used here. In particular, [IntrinsicColumnWidth] is
/// quite expensive because it needs to measure each cell in the column to
/// determine the intrinsic size of the column.
- Map<int, TableColumnWidth> get columnWidths => Map<int, TableColumnWidth>.unmodifiable(_columnWidths);
+ ///
+ /// This property can never return null. If it is set to null, and the existing
+ /// map is not empty, then the value is replaced by an empty map. (If it is set
+ /// to null while the current value is an empty map, the value is not changed.)
+ Map<int, TableColumnWidth>? get columnWidths => Map<int, TableColumnWidth>.unmodifiable(_columnWidths);
Map<int, TableColumnWidth> _columnWidths;
- set columnWidths(Map<int, TableColumnWidth> value) {
- value ??= HashMap<int, TableColumnWidth>();
+ set columnWidths(Map<int, TableColumnWidth>? value) {
if (_columnWidths == value)
return;
- _columnWidths = value;
+ if (_columnWidths.isEmpty && value == null)
+ return;
+ _columnWidths = value ?? HashMap<int, TableColumnWidth>();
markNeedsLayout();
}
@@ -510,9 +514,9 @@
}
/// The style to use when painting the boundary and interior divisions of the table.
- TableBorder get border => _border;
- TableBorder _border;
- set border(TableBorder value) {
+ TableBorder? get border => _border;
+ TableBorder? _border;
+ set border(TableBorder? value) {
if (border == value)
return;
_border = value;
@@ -527,17 +531,17 @@
List<Decoration> get rowDecorations => List<Decoration>.unmodifiable(_rowDecorations ?? const <Decoration>[]);
// _rowDecorations and _rowDecorationPainters need to be in sync. They have to
// either both be null or have same length.
- List<Decoration> _rowDecorations;
- List<BoxPainter> _rowDecorationPainters;
- set rowDecorations(List<Decoration> value) {
+ List<Decoration?>? _rowDecorations;
+ List<BoxPainter?>? _rowDecorationPainters;
+ set rowDecorations(List<Decoration?>? value) {
if (_rowDecorations == value)
return;
_rowDecorations = value;
if (_rowDecorationPainters != null) {
- for (final BoxPainter painter in _rowDecorationPainters)
+ for (final BoxPainter? painter in _rowDecorationPainters!)
painter?.dispose();
}
- _rowDecorationPainters = _rowDecorations != null ? List<BoxPainter>(_rowDecorations.length) : null;
+ _rowDecorationPainters = _rowDecorations != null ? List<BoxPainter?>.filled(_rowDecorations!.length, null, growable: false) : null;
}
/// The settings to pass to the [rowDecorations] when painting, so that they
@@ -557,6 +561,7 @@
TableCellVerticalAlignment get defaultVerticalAlignment => _defaultVerticalAlignment;
TableCellVerticalAlignment _defaultVerticalAlignment;
set defaultVerticalAlignment(TableCellVerticalAlignment value) {
+ assert(value != null);
if (_defaultVerticalAlignment == value)
return;
_defaultVerticalAlignment = value;
@@ -564,9 +569,9 @@
}
/// The text baseline to use when aligning rows using [TableCellVerticalAlignment.baseline].
- TextBaseline get textBaseline => _textBaseline;
- TextBaseline _textBaseline;
- set textBaseline(TextBaseline value) {
+ TextBaseline? get textBaseline => _textBaseline;
+ TextBaseline? _textBaseline;
+ set textBaseline(TextBaseline? value) {
if (_textBaseline == value)
return;
_textBaseline = value;
@@ -587,7 +592,7 @@
/// If the new cells contain any existing children of the table, those
/// children are simply moved to their new location in the table rather than
/// removed from the table and re-added.
- void setFlatChildren(int columns, List<RenderBox> cells) {
+ void setFlatChildren(int columns, List<RenderBox?> cells) {
if (cells == _children && columns == _columns)
return;
assert(columns >= 0);
@@ -599,7 +604,7 @@
assert(_rows == 0);
return;
}
- for (final RenderBox oldChild in _children) {
+ for (final RenderBox? oldChild in _children) {
if (oldChild != null)
dropChild(oldChild);
}
@@ -619,7 +624,7 @@
final int xyOld = x + y * _columns;
final int xyNew = x + y * columns;
if (_children[xyOld] != null && (x >= columns || xyNew >= cells.length || _children[xyOld] != cells[xyNew]))
- lostChildren.add(_children[xyOld]);
+ lostChildren.add(_children[xyOld]!);
}
}
// adopt cells that are arriving, and cross cells that are just moving off our list of lostChildren
@@ -630,7 +635,7 @@
final int xyOld = x + y * _columns;
if (cells[xyNew] != null && (x >= _columns || y >= _rows || _children[xyOld] != cells[xyNew])) {
if (!lostChildren.remove(cells[xyNew]))
- adoptChild(cells[xyNew]);
+ adoptChild(cells[xyNew]!);
}
}
y += 1;
@@ -646,13 +651,13 @@
}
/// Replaces the children of this table with the given cells.
- void setChildren(List<List<RenderBox>> cells) {
+ void setChildren(List<List<RenderBox>>? cells) {
// TODO(ianh): Make this smarter, like setFlatChildren
if (cells == null) {
- setFlatChildren(0, null);
+ setFlatChildren(0, const <RenderBox?>[]);
return;
}
- for (final RenderBox oldChild in _children) {
+ for (final RenderBox? oldChild in _children) {
if (oldChild != null)
dropChild(oldChild);
}
@@ -666,12 +671,12 @@
/// Adds a row to the end of the table.
///
/// The newly added children must not already have parents.
- void addRow(List<RenderBox> cells) {
+ void addRow(List<RenderBox?> cells) {
assert(cells.length == columns);
assert(_children.length == rows * columns);
_rows += 1;
_children.addAll(cells);
- for (final RenderBox cell in cells) {
+ for (final RenderBox? cell in cells) {
if (cell != null)
adoptChild(cell);
}
@@ -683,13 +688,13 @@
/// If the given child is already located at the given position, this function
/// does not modify the table. Otherwise, the given child must not already
/// have a parent.
- void setChild(int x, int y, RenderBox value) {
+ void setChild(int x, int y, RenderBox? value) {
assert(x != null);
assert(y != null);
assert(x >= 0 && x < columns && y >= 0 && y < rows);
assert(_children.length == rows * columns);
final int xy = x + y * columns;
- final RenderBox oldChild = _children[xy];
+ final RenderBox? oldChild = _children[xy];
if (oldChild == value)
return;
if (oldChild != null)
@@ -702,7 +707,7 @@
@override
void attach(PipelineOwner owner) {
super.attach(owner);
- for (final RenderBox child in _children)
+ for (final RenderBox? child in _children)
child?.attach(owner);
}
@@ -710,18 +715,18 @@
void detach() {
super.detach();
if (_rowDecorationPainters != null) {
- for (final BoxPainter painter in _rowDecorationPainters)
+ for (final BoxPainter? painter in _rowDecorationPainters!)
painter?.dispose();
- _rowDecorationPainters = List<BoxPainter>(_rowDecorations.length);
+ _rowDecorationPainters = List<BoxPainter?>.filled(_rowDecorations!.length, null, growable: false);
}
- for (final RenderBox child in _children)
+ for (final RenderBox? child in _children)
child?.detach();
}
@override
void visitChildren(RenderObjectVisitor visitor) {
assert(_children.length == rows * columns);
- for (final RenderBox child in _children) {
+ for (final RenderBox? child in _children) {
if (child != null)
visitor(child);
}
@@ -762,7 +767,7 @@
double rowHeight = 0.0;
for (int x = 0; x < columns; x += 1) {
final int xy = x + y * columns;
- final RenderBox child = _children[xy];
+ final RenderBox? child = _children[xy];
if (child != null)
rowHeight = math.max(rowHeight, child.getMaxIntrinsicHeight(widths[x]));
}
@@ -776,9 +781,9 @@
return computeMinIntrinsicHeight(width);
}
- double _baselineDistance;
+ double? _baselineDistance;
@override
- double computeDistanceToActualBaseline(TextBaseline baseline) {
+ double? computeDistanceToActualBaseline(TextBaseline baseline) {
// returns the baseline of the first cell that has a baseline in the first row
assert(!debugNeedsLayout);
return _baselineDistance;
@@ -791,7 +796,7 @@
Iterable<RenderBox> column(int x) sync* {
for (int y = 0; y < rows; y += 1) {
final int xy = x + y * columns;
- final RenderBox child = _children[xy];
+ final RenderBox? child = _children[xy];
if (child != null)
yield child;
}
@@ -805,7 +810,7 @@
final int start = y * columns;
final int end = (y + 1) * columns;
for (int xy = start; xy < end; xy += 1) {
- final RenderBox child = _children[xy];
+ final RenderBox? child = _children[xy];
if (child != null)
yield child;
}
@@ -825,9 +830,9 @@
// necessary, applying minimum column widths as we go
// 1. apply ideal widths, and collect information we'll need later
- final List<double> widths = List<double>(columns);
- final List<double> minWidths = List<double>(columns);
- final List<double> flexes = List<double>(columns);
+ final List<double> widths = List<double>.filled(columns, 0.0, growable: false);
+ final List<double> minWidths = List<double>.filled(columns, 0.0, growable: false);
+ final List<double?> flexes = List<double?>.filled(columns, null, growable: false);
double tableWidth = 0.0; // running tally of the sum of widths[x] for all x
double unflexedTableWidth = 0.0; // sum of the maxIntrinsicWidths of any column that has null flex
double totalFlex = 0.0;
@@ -847,17 +852,16 @@
minWidths[x] = minIntrinsicWidth;
assert(maxIntrinsicWidth >= minIntrinsicWidth);
// collect flex information while we're at it
- final double flex = columnWidth.flex(columnCells);
+ final double? flex = columnWidth.flex(columnCells);
if (flex != null) {
assert(flex.isFinite);
assert(flex > 0.0);
flexes[x] = flex;
totalFlex += flex;
} else {
- unflexedTableWidth += maxIntrinsicWidth;
+ unflexedTableWidth = unflexedTableWidth + maxIntrinsicWidth;
}
}
- assert(!widths.any((double value) => value == null));
final double maxWidthConstraint = constraints.maxWidth;
final double minWidthConstraint = constraints.minWidth;
@@ -878,7 +882,7 @@
assert(remainingWidth >= 0.0);
for (int x = 0; x < columns; x += 1) {
if (flexes[x] != null) {
- final double flexedWidth = remainingWidth * flexes[x] / totalFlex;
+ final double flexedWidth = remainingWidth * flexes[x]! / totalFlex;
assert(flexedWidth.isFinite);
assert(flexedWidth >= 0.0);
if (widths[x] < flexedWidth) {
@@ -897,15 +901,11 @@
else if (tableWidth < minWidthConstraint) {
final double delta = (minWidthConstraint - tableWidth) / columns;
for (int x = 0; x < columns; x += 1)
- widths[x] += delta;
+ widths[x] = widths[x] + delta;
tableWidth = minWidthConstraint;
}
// beyond this point, unflexedTableWidth is no longer valid
- assert(() {
- unflexedTableWidth = null;
- return true;
- }());
// 4. apply the maximum width of the table, shrinking columns as
// necessary, applying minimum column widths as we go
@@ -932,7 +932,7 @@
double newTotalFlex = 0.0;
for (int x = 0; x < columns; x += 1) {
if (flexes[x] != null) {
- final double newWidth = widths[x] - deficit * flexes[x] / totalFlex;
+ final double newWidth = widths[x] - deficit * flexes[x]! / totalFlex;
assert(newWidth.isFinite);
if (newWidth <= minWidths[x]) {
// shrank to minimum
@@ -943,7 +943,7 @@
} else {
deficit -= widths[x] - newWidth;
widths[x] = newWidth;
- newTotalFlex += flexes[x];
+ newTotalFlex += flexes[x]!;
}
assert(widths[x] >= 0.0);
}
@@ -968,7 +968,7 @@
widths[x] = minWidths[x];
} else {
deficit -= delta;
- widths[x] -= delta;
+ widths[x] = widths[x] - delta;
newAvailableColumns += 1;
}
}
@@ -981,7 +981,7 @@
// cache the table geometry for painting purposes
final List<double> _rowTops = <double>[];
- Iterable<double> _columnLefts;
+ Iterable<double>? _columnLefts;
/// Returns the position and dimensions of the box that the given
/// row covers, in this render object's coordinate space (so the
@@ -1010,7 +1010,7 @@
return;
}
final List<double> widths = _computeColumnWidths(constraints);
- final List<double> positions = List<double>(columns);
+ final List<double> positions = List<double>.filled(columns, 0.0, growable: false);
double tableWidth;
switch (textDirection) {
case TextDirection.rtl:
@@ -1028,7 +1028,6 @@
tableWidth = positions.last + widths.last;
break;
}
- assert(!positions.any((double value) => value == null));
_rowTops.clear();
_baselineDistance = null;
// then, lay out each row
@@ -1039,10 +1038,10 @@
bool haveBaseline = false;
double beforeBaselineDistance = 0.0;
double afterBaselineDistance = 0.0;
- final List<double> baselines = List<double>(columns);
+ final List<double> baselines = List<double>.filled(columns, 0.0, growable: false);
for (int x = 0; x < columns; x += 1) {
final int xy = x + y * columns;
- final RenderBox child = _children[xy];
+ final RenderBox? child = _children[xy];
if (child != null) {
final TableCellParentData childParentData = child.parentData as TableCellParentData;
assert(childParentData != null);
@@ -1052,7 +1051,7 @@
case TableCellVerticalAlignment.baseline:
assert(textBaseline != null);
child.layout(BoxConstraints.tightFor(width: widths[x]), parentUsesSize: true);
- final double childBaseline = child.getDistanceToBaseline(textBaseline, onlyReal: true);
+ final double? childBaseline = child.getDistanceToBaseline(textBaseline!, onlyReal: true);
if (childBaseline != null) {
beforeBaselineDistance = math.max(beforeBaselineDistance, childBaseline);
afterBaselineDistance = math.max(afterBaselineDistance, child.size.height - childBaseline);
@@ -1081,7 +1080,7 @@
}
for (int x = 0; x < columns; x += 1) {
final int xy = x + y * columns;
- final RenderBox child = _children[xy];
+ final RenderBox? child = _children[xy];
if (child != null) {
final TableCellParentData childParentData = child.parentData as TableCellParentData;
switch (childParentData.verticalAlignment ?? defaultVerticalAlignment) {
@@ -1113,18 +1112,18 @@
}
@override
- bool hitTestChildren(BoxHitTestResult result, { Offset position }) {
+ bool hitTestChildren(BoxHitTestResult result, { required Offset position }) {
assert(_children.length == rows * columns);
for (int index = _children.length - 1; index >= 0; index -= 1) {
- final RenderBox child = _children[index];
+ final RenderBox? child = _children[index];
if (child != null) {
final BoxParentData childParentData = child.parentData as BoxParentData;
final bool isHit = result.addWithPaintOffset(
offset: childParentData.offset,
position: position,
- hitTest: (BoxHitTestResult result, Offset transformed) {
+ hitTest: (BoxHitTestResult result, Offset? transformed) {
assert(transformed == position - childParentData.offset);
- return child.hitTest(result, position: transformed);
+ return child.hitTest(result, position: transformed!);
},
);
if (isHit)
@@ -1140,20 +1139,20 @@
if (rows * columns == 0) {
if (border != null) {
final Rect borderRect = Rect.fromLTWH(offset.dx, offset.dy, size.width, 0.0);
- border.paint(context.canvas, borderRect, rows: const <double>[], columns: const <double>[]);
+ border!.paint(context.canvas, borderRect, rows: const <double>[], columns: const <double>[]);
}
return;
}
assert(_rowTops.length == rows + 1);
if (_rowDecorations != null) {
- assert(_rowDecorations.length == _rowDecorationPainters.length);
+ assert(_rowDecorations!.length == _rowDecorationPainters!.length);
final Canvas canvas = context.canvas;
for (int y = 0; y < rows; y += 1) {
- if (_rowDecorations.length <= y)
+ if (_rowDecorations!.length <= y)
break;
- if (_rowDecorations[y] != null) {
- _rowDecorationPainters[y] ??= _rowDecorations[y].createBoxPainter(markNeedsPaint);
- _rowDecorationPainters[y].paint(
+ if (_rowDecorations![y] != null) {
+ _rowDecorationPainters![y] ??= _rowDecorations![y]!.createBoxPainter(markNeedsPaint);
+ _rowDecorationPainters![y]!.paint(
canvas,
Offset(offset.dx, offset.dy + _rowTops[y]),
configuration.copyWith(size: Size(size.width, _rowTops[y+1] - _rowTops[y])),
@@ -1162,22 +1161,22 @@
}
}
for (int index = 0; index < _children.length; index += 1) {
- final RenderBox child = _children[index];
+ final RenderBox? child = _children[index];
if (child != null) {
final BoxParentData childParentData = child.parentData as BoxParentData;
context.paintChild(child, childParentData.offset + offset);
}
}
assert(_rows == _rowTops.length - 1);
- assert(_columns == _columnLefts.length);
+ assert(_columns == _columnLefts!.length);
if (border != null) {
// The border rect might not fill the entire height of this render object
// if the rows underflow. We always force the columns to fill the width of
// the render object, which means the columns cannot underflow.
final Rect borderRect = Rect.fromLTWH(offset.dx, offset.dy, size.width, _rowTops.last);
final Iterable<double> rows = _rowTops.getRange(1, _rowTops.length - 1);
- final Iterable<double> columns = _columnLefts.skip(1);
- border.paint(context.canvas, borderRect, rows: rows, columns: columns);
+ final Iterable<double> columns = _columnLefts!.skip(1);
+ border!.paint(context.canvas, borderRect, rows: rows, columns: columns);
}
}
@@ -1189,7 +1188,7 @@
properties.add(DiagnosticsProperty<TableColumnWidth>('default column width', defaultColumnWidth));
properties.add(MessageProperty('table size', '$columns\u00D7$rows'));
properties.add(IterableProperty<String>('column offsets', _columnLefts?.map(debugFormatDouble), ifNull: 'unknown'));
- properties.add(IterableProperty<String>('row offsets', _rowTops?.map(debugFormatDouble), ifNull: 'unknown'));
+ properties.add(IterableProperty<String>('row offsets', _rowTops.map(debugFormatDouble), ifNull: 'unknown'));
}
@override
@@ -1202,7 +1201,7 @@
for (int y = 0; y < rows; y += 1) {
for (int x = 0; x < columns; x += 1) {
final int xy = x + y * columns;
- final RenderBox child = _children[xy];
+ final RenderBox? child = _children[xy];
final String name = 'child ($x, $y)';
if (child != null)
children.add(child.toDiagnosticsNode(name: name));
diff --git a/packages/flutter/lib/src/rendering/table_border.dart b/packages/flutter/lib/src/rendering/table_border.dart
index 1a5a99a..4a16505 100644
--- a/packages/flutter/lib/src/rendering/table_border.dart
+++ b/packages/flutter/lib/src/rendering/table_border.dart
@@ -2,8 +2,6 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-// @dart = 2.8
-
import 'package:flutter/foundation.dart';
import 'package:flutter/painting.dart' hide Border;
@@ -150,12 +148,12 @@
/// borders.
///
/// {@macro dart.ui.shadow.lerp}
- static TableBorder lerp(TableBorder a, TableBorder b, double t) {
+ static TableBorder? lerp(TableBorder? a, TableBorder? b, double t) {
assert(t != null);
if (a == null && b == null)
return null;
if (a == null)
- return b.scale(t);
+ return b!.scale(t);
if (b == null)
return a.scale(1.0 - t);
return TableBorder(
@@ -197,8 +195,8 @@
void paint(
Canvas canvas,
Rect rect, {
- @required Iterable<double> rows,
- @required Iterable<double> columns,
+ required Iterable<double> rows,
+ required Iterable<double> columns,
}) {
// properties can't be null
assert(top != null);
diff --git a/packages/flutter/lib/src/rendering/texture.dart b/packages/flutter/lib/src/rendering/texture.dart
index 828c41c..aa991d1 100644
--- a/packages/flutter/lib/src/rendering/texture.dart
+++ b/packages/flutter/lib/src/rendering/texture.dart
@@ -2,9 +2,6 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-// @dart = 2.8
-
-import 'package:flutter/foundation.dart';
import 'box.dart';
import 'layer.dart';
import 'object.dart';
@@ -40,7 +37,7 @@
/// Creates a box backed by the texture identified by [textureId], and use
/// [filterQuality] to set texture's [FilterQuality].
TextureBox({
- @required int textureId,
+ required int textureId,
FilterQuality filterQuality = FilterQuality.low,
}) : assert(textureId != null),
_textureId = textureId,
@@ -87,8 +84,6 @@
@override
void paint(PaintingContext context, Offset offset) {
- if (_textureId == null)
- return;
context.addLayer(TextureLayer(
rect: Rect.fromLTWH(offset.dx, offset.dy, size.width, size.height),
textureId: _textureId,
diff --git a/packages/flutter/lib/src/rendering/tweens.dart b/packages/flutter/lib/src/rendering/tweens.dart
index 0f010f2..5d2e9ad 100644
--- a/packages/flutter/lib/src/rendering/tweens.dart
+++ b/packages/flutter/lib/src/rendering/tweens.dart
@@ -2,8 +2,6 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-// @dart = 2.8
-
import 'package:flutter/animation.dart';
import 'package:flutter/painting.dart';
@@ -17,17 +15,17 @@
/// See also:
///
/// * [AlignmentTween], which interpolates between to [Alignment] objects.
-class FractionalOffsetTween extends Tween<FractionalOffset> {
+class FractionalOffsetTween extends Tween<FractionalOffset?> {
/// Creates a fractional offset tween.
///
/// The [begin] and [end] properties may be null; the null value
/// is treated as meaning the center.
- FractionalOffsetTween({ FractionalOffset begin, FractionalOffset end })
+ FractionalOffsetTween({ FractionalOffset? begin, FractionalOffset? end })
: super(begin: begin, end: end);
/// Returns the value this variable has at the given animation clock value.
@override
- FractionalOffset lerp(double t) => FractionalOffset.lerp(begin, end, t);
+ FractionalOffset? lerp(double t) => FractionalOffset.lerp(begin, end, t);
}
/// An interpolation between two alignments.
@@ -41,17 +39,17 @@
///
/// * [AlignmentGeometryTween], which interpolates between two
/// [AlignmentGeometry] objects.
-class AlignmentTween extends Tween<Alignment> {
+class AlignmentTween extends Tween<Alignment?> {
/// Creates a fractional offset tween.
///
/// The [begin] and [end] properties may be null; the null value
/// is treated as meaning the center.
- AlignmentTween({ Alignment begin, Alignment end })
+ AlignmentTween({ Alignment? begin, Alignment? end })
: super(begin: begin, end: end);
/// Returns the value this variable has at the given animation clock value.
@override
- Alignment lerp(double t) => Alignment.lerp(begin, end, t);
+ Alignment? lerp(double t) => Alignment.lerp(begin, end, t);
}
/// An interpolation between two [AlignmentGeometry].
@@ -64,17 +62,17 @@
/// See also:
///
/// * [AlignmentTween], which interpolates between two [Alignment] objects.
-class AlignmentGeometryTween extends Tween<AlignmentGeometry> {
+class AlignmentGeometryTween extends Tween<AlignmentGeometry?> {
/// Creates a fractional offset geometry tween.
///
/// The [begin] and [end] properties may be null; the null value
/// is treated as meaning the center.
AlignmentGeometryTween({
- AlignmentGeometry begin,
- AlignmentGeometry end,
+ AlignmentGeometry? begin,
+ AlignmentGeometry? end,
}) : super(begin: begin, end: end);
/// Returns the value this variable has at the given animation clock value.
@override
- AlignmentGeometry lerp(double t) => AlignmentGeometry.lerp(begin, end, t);
+ AlignmentGeometry? lerp(double t) => AlignmentGeometry.lerp(begin, end, t);
}
diff --git a/packages/flutter/lib/src/rendering/view.dart b/packages/flutter/lib/src/rendering/view.dart
index dee0c07..a17a318 100644
--- a/packages/flutter/lib/src/rendering/view.dart
+++ b/packages/flutter/lib/src/rendering/view.dart
@@ -2,8 +2,6 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-// @dart = 2.8
-
import 'dart:developer';
import 'dart:io' show Platform;
import 'dart:ui' as ui show Scene, SceneBuilder, Window;
@@ -57,9 +55,9 @@
///
/// The [configuration] must not be null.
RenderView({
- RenderBox child,
- @required ViewConfiguration configuration,
- @required ui.Window window,
+ RenderBox? child,
+ required ViewConfiguration configuration,
+ required ui.Window window,
}) : assert(configuration != null),
_configuration = configuration,
_window = window {
@@ -120,7 +118,7 @@
)
void scheduleInitialFrame() {
prepareInitialFrame();
- owner.requestVisualUpdate();
+ owner!.requestVisualUpdate();
}
/// Bootstrap the rendering pipeline by preparing the first frame.
@@ -139,7 +137,7 @@
assert(_rootTransform != null);
}
- Matrix4 _rootTransform;
+ Matrix4? _rootTransform;
TransformLayer _updateMatricesAndCreateNewRootLayer() {
_rootTransform = configuration.toMatrix();
@@ -166,11 +164,11 @@
assert(_size.isFinite);
if (child != null)
- child.layout(BoxConstraints.tight(_size));
+ child!.layout(BoxConstraints.tight(_size));
}
@override
- void rotate({ int oldAngle, int newAngle, Duration time }) {
+ void rotate({ int? oldAngle, int? newAngle, Duration? time }) {
assert(false); // nobody tells the screen to rotate, the whole rotate() dance is started from our performResize()
}
@@ -184,9 +182,9 @@
/// which is to say, in logical pixels. This is not necessarily the same
/// coordinate system as that expected by the root [Layer], which will
/// normally be in physical (device) pixels.
- bool hitTest(HitTestResult result, { Offset position }) {
+ bool hitTest(HitTestResult result, { required Offset position }) {
if (child != null)
- child.hitTest(BoxHitTestResult.wrap(result), position: position);
+ child!.hitTest(BoxHitTestResult.wrap(result), position: position);
result.add(HitTestEntry(this));
return true;
}
@@ -198,6 +196,7 @@
/// * [Layer.findAllAnnotations], which is used by this method to find all
/// [AnnotatedRegionLayer]s annotated for mouse tracking.
HitTestResult hitTestMouseTrackers(Offset position) {
+ assert(position != null);
// Layer hit testing is done using device pixels, so we have to convert
// the logical coordinates of the event location back to device pixels
// here.
@@ -212,13 +211,13 @@
@override
void paint(PaintingContext context, Offset offset) {
if (child != null)
- context.paintChild(child, offset);
+ context.paintChild(child!, offset);
}
@override
void applyPaintTransform(RenderBox child, Matrix4 transform) {
assert(_rootTransform != null);
- transform.multiply(_rootTransform);
+ transform.multiply(_rootTransform!);
super.applyPaintTransform(child, transform);
}
@@ -229,7 +228,7 @@
Timeline.startSync('Compositing', arguments: timelineArgumentsIndicatingLandmarkEvent);
try {
final ui.SceneBuilder builder = ui.SceneBuilder();
- final ui.Scene scene = layer.buildScene(builder);
+ final ui.Scene scene = layer!.buildScene(builder);
if (automaticSystemUiAdjustment)
_updateSystemChrome();
_window.render(scene);
@@ -248,12 +247,12 @@
final Rect bounds = paintBounds;
final Offset top = Offset(bounds.center.dx, _window.padding.top / _window.devicePixelRatio);
final Offset bottom = Offset(bounds.center.dx, bounds.center.dy - _window.padding.bottom / _window.devicePixelRatio);
- final SystemUiOverlayStyle upperOverlayStyle = layer.find<SystemUiOverlayStyle>(top);
+ final SystemUiOverlayStyle? upperOverlayStyle = layer!.find<SystemUiOverlayStyle>(top);
// Only android has a customizable system navigation bar.
- SystemUiOverlayStyle lowerOverlayStyle;
+ SystemUiOverlayStyle? lowerOverlayStyle;
switch (defaultTargetPlatform) {
case TargetPlatform.android:
- lowerOverlayStyle = layer.find<SystemUiOverlayStyle>(bottom);
+ lowerOverlayStyle = layer!.find<SystemUiOverlayStyle>(bottom);
break;
case TargetPlatform.fuchsia:
case TargetPlatform.iOS:
@@ -282,7 +281,7 @@
@override
Rect get semanticBounds {
assert(_rootTransform != null);
- return MatrixUtils.transformRect(_rootTransform, Offset.zero & size);
+ return MatrixUtils.transformRect(_rootTransform!, Offset.zero & size);
}
@override
diff --git a/packages/flutter/lib/src/rendering/viewport.dart b/packages/flutter/lib/src/rendering/viewport.dart
index e6410b0..4497ddc 100644
--- a/packages/flutter/lib/src/rendering/viewport.dart
+++ b/packages/flutter/lib/src/rendering/viewport.dart
@@ -2,8 +2,6 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-// @dart = 2.8
-
import 'dart:math' as math;
import 'package:flutter/animation.dart';
@@ -35,18 +33,18 @@
// This class is intended to be used as an interface, and should not be
// extended directly; this constructor prevents instantiation and extension.
// ignore: unused_element
- factory RenderAbstractViewport._() => null;
+ factory RenderAbstractViewport._() => throw Error();
/// Returns the [RenderAbstractViewport] that most tightly encloses the given
/// render object.
///
/// If the object does not have a [RenderAbstractViewport] as an ancestor,
/// this function returns null.
- static RenderAbstractViewport of(RenderObject object) {
+ static RenderAbstractViewport? of(RenderObject? object) {
while (object != null) {
if (object is RenderAbstractViewport)
return object;
- object = object.parent as RenderObject;
+ object = object.parent as RenderObject?;
}
return null;
}
@@ -78,15 +76,15 @@
/// See also:
///
/// * [RevealedOffset], which describes the return value of this method.
- RevealedOffset getOffsetToReveal(RenderObject target, double alignment, { Rect rect });
+ RevealedOffset getOffsetToReveal(RenderObject target, double alignment, { Rect? rect });
/// The default value for the cache extent of the viewport.
///
+ /// This default assumes [CacheExtentStyle.pixel].
+ ///
/// See also:
///
/// * [RenderViewportBase.cacheExtent] for a definition of the cache extent.
- @protected
- @visibleForTesting
static const double defaultCacheExtent = 250.0;
}
@@ -99,8 +97,8 @@
/// Instantiates a return value for [RenderAbstractViewport.getOffsetToReveal].
const RevealedOffset({
- @required this.offset,
- @required this.rect,
+ required this.offset,
+ required this.rect,
}) : assert(offset != null),
assert(rect != null);
@@ -167,11 +165,15 @@
extends RenderBox with ContainerRenderObjectMixin<RenderSliver, ParentDataClass>
implements RenderAbstractViewport {
/// Initializes fields for subclasses.
+ ///
+ /// The [cacheExtent], if null, defaults to [RenderAbstractViewport.defaultCacheExtent].
+ ///
+ /// The [cacheExtent] must be specified if [cacheExtentStyle] is not [CacheExtentStyle.pixel].
RenderViewportBase({
AxisDirection axisDirection = AxisDirection.down,
- @required AxisDirection crossAxisDirection,
- @required ViewportOffset offset,
- double cacheExtent,
+ required AxisDirection crossAxisDirection,
+ required ViewportOffset offset,
+ double? cacheExtent,
CacheExtentStyle cacheExtentStyle = CacheExtentStyle.pixel,
Clip clipBehavior = Clip.hardEdge,
}) : assert(axisDirection != null),
@@ -213,7 +215,7 @@
@override
void visitChildrenForSemantics(RenderObjectVisitor visitor) {
childrenInPaintOrder
- .where((RenderSliver sliver) => sliver.geometry.visible || sliver.geometry.cacheExtent > 0.0)
+ .where((RenderSliver sliver) => sliver.geometry!.visible || sliver.geometry!.cacheExtent > 0.0)
.forEach(visitor);
}
@@ -277,6 +279,11 @@
markNeedsLayout();
}
+ // TODO(ianh): cacheExtent/cacheExtentStyle should be a single
+ // object that specifies both the scalar value and the unit, not a
+ // pair of independent setters. Changing that would allow a more
+ // rational API and would let us make the getter non-nullable.
+
/// {@template flutter.rendering.viewport.cacheExtent}
/// The viewport has an area before and after the visible area to cache items
/// that are about to become visible when the user scrolls.
@@ -295,10 +302,19 @@
/// viewport to an invisible item in the cache area, the framework will bring
/// that item into view with an (implicit) scroll action.
/// {@endtemplate}
- double get cacheExtent => _cacheExtent;
+ ///
+ /// The getter can never return null, but the field is nullable
+ /// because the setter can be set to null to reset the value to
+ /// [RenderAbstractViewport.defaultCacheExtent] (in which case
+ /// [cacheExtentStyle] must be [CacheExtentStyle.pixel]).
+ ///
+ /// See also:
+ ///
+ /// * [cacheExtentStyle], which controls the units of the [cacheExtent].
+ double? get cacheExtent => _cacheExtent;
double _cacheExtent;
- set cacheExtent(double value) {
- value = value ?? RenderAbstractViewport.defaultCacheExtent;
+ set cacheExtent(double? value) {
+ value ??= RenderAbstractViewport.defaultCacheExtent;
assert(value != null);
if (value == _cacheExtent)
return;
@@ -311,18 +327,23 @@
/// When the style is [CacheExtentStyle.viewport], it is the main axis extent
/// of the viewport multiplied by the requested cache extent, which is still
/// expressed in pixels.
- double _calculatedCacheExtent;
+ double? _calculatedCacheExtent;
/// {@template flutter.rendering.viewport.cacheExtentStyle}
/// Controls how the [cacheExtent] is interpreted.
///
- /// If set to [CacheExtentStyle.pixel], the [cacheExtent] will be treated as
- /// a logical pixels.
+ /// If set to [CacheExtentStyle.pixel], the [cacheExtent] will be
+ /// treated as a logical pixels, and the default [cacheExtent] is
+ /// [RenderAbstractViewport.defaultCacheExtent].
///
- /// If set to [CacheExtentStyle.viewport], the [cacheExtent] will be treated
- /// as a multiplier for the main axis extent of the viewport. In this case,
- /// the [cacheExtent] must not be null.
+ /// If set to [CacheExtentStyle.viewport], the [cacheExtent] will be
+ /// treated as a multiplier for the main axis extent of the
+ /// viewport. In this case there is no default [cacheExtent]; it
+ /// must be explicitly specified.
/// {@endtemplate}
+ ///
+ /// Changing the [cacheExtentStyle] without also changing the [cacheExtent]
+ /// is rarely the correct choice.
CacheExtentStyle get cacheExtentStyle => _cacheExtentStyle;
CacheExtentStyle _cacheExtentStyle;
set cacheExtentStyle(CacheExtentStyle value) {
@@ -449,17 +470,17 @@
/// function repeatedly until it returns 0.0.
@protected
double layoutChildSequence({
- @required RenderSliver child,
- @required double scrollOffset,
- @required double overlap,
- @required double layoutOffset,
- @required double remainingPaintExtent,
- @required double mainAxisExtent,
- @required double crossAxisExtent,
- @required GrowthDirection growthDirection,
- @required RenderSliver advance(RenderSliver child),
- @required double remainingCacheExtent,
- @required double cacheOrigin,
+ required RenderSliver? child,
+ required double scrollOffset,
+ required double overlap,
+ required double layoutOffset,
+ required double remainingPaintExtent,
+ required double mainAxisExtent,
+ required double crossAxisExtent,
+ required GrowthDirection growthDirection,
+ required RenderSliver? Function(RenderSliver child) advance,
+ required double remainingCacheExtent,
+ required double cacheOrigin,
}) {
assert(scrollOffset.isFinite);
assert(scrollOffset >= 0.0);
@@ -498,12 +519,12 @@
cacheOrigin: correctedCacheOrigin,
), parentUsesSize: true);
- final SliverGeometry childLayoutGeometry = child.geometry;
+ final SliverGeometry childLayoutGeometry = child.geometry!;
assert(childLayoutGeometry.debugAssertIsValid());
// If there is a correction to apply, we'll have to start over.
if (childLayoutGeometry.scrollOffsetCorrection != null)
- return childLayoutGeometry.scrollOffsetCorrection;
+ return childLayoutGeometry.scrollOffsetCorrection!;
// We use the child's paint origin in our coordinate system as the
// layoutOffset we store in the child's parent data.
@@ -578,7 +599,7 @@
}
@override
- Rect describeSemanticsClip(RenderSliver child) {
+ Rect describeSemanticsClip(RenderSliver? child) {
assert(axis != null);
if (_calculatedCacheExtent == null) {
@@ -589,19 +610,18 @@
case Axis.vertical:
return Rect.fromLTRB(
semanticBounds.left,
- semanticBounds.top - _calculatedCacheExtent,
+ semanticBounds.top - _calculatedCacheExtent!,
semanticBounds.right,
- semanticBounds.bottom + _calculatedCacheExtent,
+ semanticBounds.bottom + _calculatedCacheExtent!,
);
case Axis.horizontal:
return Rect.fromLTRB(
- semanticBounds.left - _calculatedCacheExtent,
+ semanticBounds.left - _calculatedCacheExtent!,
semanticBounds.top,
- semanticBounds.right + _calculatedCacheExtent,
+ semanticBounds.right + _calculatedCacheExtent!,
semanticBounds.bottom,
);
}
- return null;
}
@override
@@ -617,7 +637,7 @@
void _paintContents(PaintingContext context, Offset offset) {
for (final RenderSliver child in childrenInPaintOrder) {
- if (child.geometry.visible)
+ if (child.geometry!.visible)
context.paintChild(child, offset + paintOffsetOf(child));
}
}
@@ -631,15 +651,15 @@
..strokeWidth = 1.0
..color = const Color(0xFF00FF00);
final Canvas canvas = context.canvas;
- RenderSliver child = firstChild;
+ RenderSliver? child = firstChild;
while (child != null) {
Size size;
switch (axis) {
case Axis.vertical:
- size = Size(child.constraints.crossAxisExtent, child.geometry.layoutExtent);
+ size = Size(child.constraints.crossAxisExtent, child.geometry!.layoutExtent);
break;
case Axis.horizontal:
- size = Size(child.geometry.layoutExtent, child.constraints.crossAxisExtent);
+ size = Size(child.geometry!.layoutExtent, child.constraints.crossAxisExtent);
break;
}
assert(size != null);
@@ -651,7 +671,7 @@
}
@override
- bool hitTestChildren(BoxHitTestResult result, { Offset position }) {
+ bool hitTestChildren(BoxHitTestResult result, { required Offset position }) {
double mainAxisPosition, crossAxisPosition;
switch (axis) {
case Axis.vertical:
@@ -667,15 +687,14 @@
assert(crossAxisPosition != null);
final SliverHitTestResult sliverResult = SliverHitTestResult.wrap(result);
for (final RenderSliver child in childrenInHitTestOrder) {
- if (!child.geometry.visible) {
+ if (!child.geometry!.visible) {
continue;
}
final Matrix4 transform = Matrix4.identity();
- applyPaintTransform(child, transform);
- final bool isHit = result.addWithPaintTransform(
- transform: transform,
- position: null, // Manually adapting from box to sliver position below.
- hitTest: (BoxHitTestResult result, Offset _) {
+ applyPaintTransform(child, transform); // must be invertible
+ final bool isHit = result.addWithOutOfBandPosition(
+ paintTransform: transform,
+ hitTest: (BoxHitTestResult result) {
return child.hitTest(
sliverResult,
mainAxisPosition: computeChildMainAxisPosition(child, mainAxisPosition),
@@ -691,7 +710,7 @@
}
@override
- RevealedOffset getOffsetToReveal(RenderObject target, double alignment, { Rect rect }) {
+ RevealedOffset getOffsetToReveal(RenderObject target, double alignment, { Rect? rect }) {
// Steps to convert `rect` (from a RenderBox coordinate system) to its
// scroll offset within this viewport (not in the exact order):
//
@@ -714,7 +733,7 @@
// - `child` will be the last object before we reach this viewport, and
// - `pivot` will be the last RenderBox before we reach this viewport.
RenderObject child = target;
- RenderBox pivot;
+ RenderBox? pivot;
bool onlySlivers = target is RenderSliver; // ... between viewport and `target` (`target` included).
while (child.parent != this) {
final RenderObject parent = child.parent as RenderObject;
@@ -723,7 +742,7 @@
pivot = child;
}
if (parent is RenderSliver) {
- leadingScrollOffset += parent.childScrollOffset(child);
+ leadingScrollOffset += parent.childScrollOffset(child)!;
} else {
onlySlivers = false;
leadingScrollOffset = 0.0;
@@ -763,13 +782,13 @@
growthDirection = targetSliver.constraints.growthDirection;
// TODO(LongCatIsLooong): make sure this works if `targetSliver` is a
// persistent header, when #56413 relands.
- pivotExtent = targetSliver.geometry.scrollExtent;
+ pivotExtent = targetSliver.geometry!.scrollExtent;
if (rect == null) {
switch (axis) {
case Axis.horizontal:
rect = Rect.fromLTWH(
0, 0,
- targetSliver.geometry.scrollExtent,
+ targetSliver.geometry!.scrollExtent,
targetSliver.constraints.crossAxisExtent,
);
break;
@@ -777,14 +796,15 @@
rect = Rect.fromLTWH(
0, 0,
targetSliver.constraints.crossAxisExtent,
- targetSliver.geometry.scrollExtent,
+ targetSliver.geometry!.scrollExtent,
);
break;
}
}
rectLocal = rect;
} else {
- return RevealedOffset(offset: offset.pixels, rect: rect);
+ assert(rect != null);
+ return RevealedOffset(offset: offset.pixels, rect: rect!);
}
assert(pivotExtent != null);
@@ -894,15 +914,14 @@
assert(child.geometry != null);
switch (applyGrowthDirectionToAxisDirection(axisDirection, growthDirection)) {
case AxisDirection.up:
- return Offset(0.0, size.height - (layoutOffset + child.geometry.paintExtent));
+ return Offset(0.0, size.height - (layoutOffset + child.geometry!.paintExtent));
case AxisDirection.right:
return Offset(layoutOffset, 0.0);
case AxisDirection.down:
return Offset(0.0, layoutOffset);
case AxisDirection.left:
- return Offset(size.width - (layoutOffset + child.geometry.paintExtent), 0.0);
+ return Offset(size.width - (layoutOffset + child.geometry!.paintExtent), 0.0);
}
- return null;
}
@override
@@ -916,13 +935,13 @@
@override
List<DiagnosticsNode> debugDescribeChildren() {
final List<DiagnosticsNode> children = <DiagnosticsNode>[];
- RenderSliver child = firstChild;
+ RenderSliver? child = firstChild;
if (child == null)
return children;
int count = indexOfFirstChild;
while (true) {
- children.add(child.toDiagnosticsNode(name: labelForChild(count)));
+ children.add(child!.toDiagnosticsNode(name: labelForChild(count)));
if (child == lastChild)
break;
count += 1;
@@ -1043,8 +1062,8 @@
@override
void showOnScreen({
- RenderObject descendant,
- Rect rect,
+ RenderObject? descendant,
+ Rect? rect,
Duration duration = Duration.zero,
Curve curve = Curves.ease,
}) {
@@ -1057,7 +1076,7 @@
);
}
- final Rect newRect = RenderViewportBase.showInViewport(
+ final Rect? newRect = RenderViewportBase.showInViewport(
descendant: descendant,
viewport: this,
offset: offset,
@@ -1098,11 +1117,11 @@
///
/// * [RenderObject.showOnScreen], overridden by [RenderViewportBase] and the
/// renderer for [SingleChildScrollView] to delegate to this method.
- static Rect showInViewport({
- RenderObject descendant,
- Rect rect,
- @required RenderAbstractViewport viewport,
- @required ViewportOffset offset,
+ static Rect? showInViewport({
+ RenderObject? descendant,
+ Rect? rect,
+ required RenderAbstractViewport viewport,
+ required ViewportOffset offset,
Duration duration = Duration.zero,
Curve curve = Curves.ease,
}) {
@@ -1206,12 +1225,12 @@
/// [new ViewportOffset.zero] or [new ViewportOffset.fixed].
RenderViewport({
AxisDirection axisDirection = AxisDirection.down,
- @required AxisDirection crossAxisDirection,
- @required ViewportOffset offset,
+ required AxisDirection crossAxisDirection,
+ required ViewportOffset offset,
double anchor = 0.0,
- List<RenderSliver> children,
- RenderSliver center,
- double cacheExtent,
+ List<RenderSliver>? children,
+ RenderSliver? center,
+ double? cacheExtent,
CacheExtentStyle cacheExtentStyle = CacheExtentStyle.pixel,
Clip clipBehavior = Clip.hardEdge,
}) : assert(anchor != null),
@@ -1302,9 +1321,9 @@
/// the [axisDirection] relative to the [center].
///
/// The [center] must be a child of the viewport.
- RenderSliver get center => _center;
- RenderSliver _center;
- set center(RenderSliver value) {
+ RenderSliver? get center => _center;
+ RenderSliver? _center;
+ set center(RenderSliver? value) {
if (value == _center)
return;
_center = value;
@@ -1389,8 +1408,8 @@
static const int _maxLayoutCycles = 10;
// Out-of-band data computed during layout.
- double _minScrollExtent;
- double _maxScrollExtent;
+ late double _minScrollExtent;
+ late double _maxScrollExtent;
bool _hasVisualOverflow = false;
@override
@@ -1414,7 +1433,7 @@
offset.applyContentDimensions(0.0, 0.0);
return;
}
- assert(center.parent == this);
+ assert(center!.parent == this);
double mainAxisExtent;
double crossAxisExtent;
@@ -1429,7 +1448,7 @@
break;
}
- final double centerOffsetAdjustment = center.centerOffsetAdjustment;
+ final double centerOffsetAdjustment = center!.centerOffsetAdjustment;
double correction;
int count = 0;
@@ -1487,24 +1506,24 @@
// to the zero scroll offset (the line between the forward slivers and the
// reverse slivers).
final double centerOffset = mainAxisExtent * anchor - correctedOffset;
- final double reverseDirectionRemainingPaintExtent = centerOffset.clamp(0.0, mainAxisExtent) as double;
- final double forwardDirectionRemainingPaintExtent = (mainAxisExtent - centerOffset).clamp(0.0, mainAxisExtent) as double;
+ final double reverseDirectionRemainingPaintExtent = centerOffset.clamp(0.0, mainAxisExtent);
+ final double forwardDirectionRemainingPaintExtent = (mainAxisExtent - centerOffset).clamp(0.0, mainAxisExtent);
switch (cacheExtentStyle) {
case CacheExtentStyle.pixel:
_calculatedCacheExtent = cacheExtent;
break;
case CacheExtentStyle.viewport:
- _calculatedCacheExtent = mainAxisExtent * cacheExtent;
+ _calculatedCacheExtent = mainAxisExtent * _cacheExtent;
break;
}
- final double fullCacheExtent = mainAxisExtent + 2 * _calculatedCacheExtent;
- final double centerCacheOffset = centerOffset + _calculatedCacheExtent;
- final double reverseDirectionRemainingCacheExtent = centerCacheOffset.clamp(0.0, fullCacheExtent) as double;
- final double forwardDirectionRemainingCacheExtent = (fullCacheExtent - centerCacheOffset).clamp(0.0, fullCacheExtent) as double;
+ final double fullCacheExtent = mainAxisExtent + 2 * _calculatedCacheExtent!;
+ final double centerCacheOffset = centerOffset + _calculatedCacheExtent!;
+ final double reverseDirectionRemainingCacheExtent = centerCacheOffset.clamp(0.0, fullCacheExtent);
+ final double forwardDirectionRemainingCacheExtent = (fullCacheExtent - centerCacheOffset).clamp(0.0, fullCacheExtent);
- final RenderSliver leadingNegativeChild = childBefore(center);
+ final RenderSliver? leadingNegativeChild = childBefore(center!);
if (leadingNegativeChild != null) {
// negative scroll offsets
@@ -1519,7 +1538,7 @@
growthDirection: GrowthDirection.reverse,
advance: childBefore,
remainingCacheExtent: reverseDirectionRemainingCacheExtent,
- cacheOrigin: (mainAxisExtent - centerOffset).clamp(-_calculatedCacheExtent, 0.0) as double,
+ cacheOrigin: (mainAxisExtent - centerOffset).clamp(-_calculatedCacheExtent!, 0.0),
);
if (result != 0.0)
return -result;
@@ -1537,7 +1556,7 @@
growthDirection: GrowthDirection.forward,
advance: childAfter,
remainingCacheExtent: forwardDirectionRemainingCacheExtent,
- cacheOrigin: centerOffset.clamp(-_calculatedCacheExtent, 0.0) as double,
+ cacheOrigin: centerOffset.clamp(-_calculatedCacheExtent!, 0.0),
);
}
@@ -1578,22 +1597,21 @@
switch (growthDirection) {
case GrowthDirection.forward:
double scrollOffsetToChild = 0.0;
- RenderSliver current = center;
+ RenderSliver? current = center;
while (current != child) {
- scrollOffsetToChild += current.geometry.scrollExtent;
+ scrollOffsetToChild += current!.geometry!.scrollExtent;
current = childAfter(current);
}
return scrollOffsetToChild + scrollOffsetWithinChild;
case GrowthDirection.reverse:
double scrollOffsetToChild = 0.0;
- RenderSliver current = childBefore(center);
+ RenderSliver? current = childBefore(center!);
while (current != child) {
- scrollOffsetToChild -= current.geometry.scrollExtent;
+ scrollOffsetToChild -= current!.geometry!.scrollExtent;
current = childBefore(current);
}
return scrollOffsetToChild - scrollOffsetWithinChild;
}
- return null;
}
@override
@@ -1604,26 +1622,26 @@
switch (growthDirection) {
case GrowthDirection.forward:
double pinnedExtent = 0.0;
- RenderSliver current = center;
+ RenderSliver? current = center;
while (current != child) {
- pinnedExtent += current.geometry.maxScrollObstructionExtent;
+ pinnedExtent += current!.geometry!.maxScrollObstructionExtent;
current = childAfter(current);
}
return pinnedExtent;
case GrowthDirection.reverse:
double pinnedExtent = 0.0;
- RenderSliver current = childBefore(center);
+ RenderSliver? current = childBefore(center!);
while (current != child) {
- pinnedExtent += current.geometry.maxScrollObstructionExtent;
+ pinnedExtent += current!.geometry!.maxScrollObstructionExtent;
current = childBefore(current);
}
return pinnedExtent;
}
- return null;
}
@override
void applyPaintTransform(RenderObject child, Matrix4 transform) {
+ // Hit test logic relies on this always providing an invertible matrix.
assert(child != null);
final SliverPhysicalParentData childParentData = child.parentData as SliverPhysicalParentData;
childParentData.applyPaintTransform(transform);
@@ -1640,23 +1658,22 @@
case AxisDirection.right:
return parentMainAxisPosition - childParentData.paintOffset.dx;
case AxisDirection.up:
- return child.geometry.paintExtent - (parentMainAxisPosition - childParentData.paintOffset.dy);
+ return child.geometry!.paintExtent - (parentMainAxisPosition - childParentData.paintOffset.dy);
case AxisDirection.left:
- return child.geometry.paintExtent - (parentMainAxisPosition - childParentData.paintOffset.dx);
+ return child.geometry!.paintExtent - (parentMainAxisPosition - childParentData.paintOffset.dx);
}
- return 0.0;
}
@override
int get indexOfFirstChild {
assert(center != null);
- assert(center.parent == this);
+ assert(center!.parent == this);
assert(firstChild != null);
int count = 0;
- RenderSliver child = center;
+ RenderSliver? child = center;
while (child != firstChild) {
count -= 1;
- child = childBefore(child);
+ child = childBefore(child!);
}
return count;
}
@@ -1672,14 +1689,14 @@
Iterable<RenderSliver> get childrenInPaintOrder sync* {
if (firstChild == null)
return;
- RenderSliver child = firstChild;
+ RenderSliver? child = firstChild;
while (child != center) {
- yield child;
+ yield child!;
child = childAfter(child);
}
child = lastChild;
while (true) {
- yield child;
+ yield child!;
if (child == center)
return;
child = childBefore(child);
@@ -1690,12 +1707,12 @@
Iterable<RenderSliver> get childrenInHitTestOrder sync* {
if (firstChild == null)
return;
- RenderSliver child = center;
+ RenderSliver? child = center;
while (child != null) {
yield child;
child = childAfter(child);
}
- child = childBefore(center);
+ child = childBefore(center!);
while (child != null) {
yield child;
child = childBefore(child);
@@ -1742,10 +1759,10 @@
/// [new ViewportOffset.zero] or [new ViewportOffset.fixed].
RenderShrinkWrappingViewport({
AxisDirection axisDirection = AxisDirection.down,
- @required AxisDirection crossAxisDirection,
- @required ViewportOffset offset,
+ required AxisDirection crossAxisDirection,
+ required ViewportOffset offset,
Clip clipBehavior = Clip.hardEdge,
- List<RenderSliver> children,
+ List<RenderSliver>? children,
}) : super(
axisDirection: axisDirection,
crossAxisDirection: crossAxisDirection,
@@ -1784,8 +1801,8 @@
}
// Out-of-band data computed during layout.
- double _maxScrollExtent;
- double _shrinkWrapExtent;
+ late double _maxScrollExtent;
+ late double _shrinkWrapExtent;
bool _hasVisualOverflow = false;
@override
@@ -1881,8 +1898,8 @@
crossAxisExtent: crossAxisExtent,
growthDirection: GrowthDirection.forward,
advance: childAfter,
- remainingCacheExtent: mainAxisExtent + 2 * cacheExtent,
- cacheOrigin: -cacheExtent,
+ remainingCacheExtent: mainAxisExtent + 2 * _cacheExtent,
+ cacheOrigin: -_cacheExtent,
);
}
@@ -1908,7 +1925,7 @@
@override
Offset paintOffsetOf(RenderSliver child) {
final SliverLogicalParentData childParentData = child.parentData as SliverLogicalParentData;
- return computeAbsolutePaintOffset(child, childParentData.layoutOffset, GrowthDirection.forward);
+ return computeAbsolutePaintOffset(child, childParentData.layoutOffset!, GrowthDirection.forward);
}
@override
@@ -1916,9 +1933,9 @@
assert(child.parent == this);
assert(child.constraints.growthDirection == GrowthDirection.forward);
double scrollOffsetToChild = 0.0;
- RenderSliver current = firstChild;
+ RenderSliver? current = firstChild;
while (current != child) {
- scrollOffsetToChild += current.geometry.scrollExtent;
+ scrollOffsetToChild += current!.geometry!.scrollExtent;
current = childAfter(current);
}
return scrollOffsetToChild + scrollOffsetWithinChild;
@@ -1929,9 +1946,9 @@
assert(child.parent == this);
assert(child.constraints.growthDirection == GrowthDirection.forward);
double pinnedExtent = 0.0;
- RenderSliver current = firstChild;
+ RenderSliver? current = firstChild;
while (current != child) {
- pinnedExtent += current.geometry.maxScrollObstructionExtent;
+ pinnedExtent += current!.geometry!.maxScrollObstructionExtent;
current = childAfter(current);
}
return pinnedExtent;
@@ -1939,6 +1956,7 @@
@override
void applyPaintTransform(RenderObject child, Matrix4 transform) {
+ // Hit test logic relies on this always providing an invertible matrix.
assert(child != null);
final Offset offset = paintOffsetOf(child as RenderSliver);
transform.translate(offset.dx, offset.dy);
@@ -1953,13 +1971,12 @@
switch (applyGrowthDirectionToAxisDirection(child.constraints.axisDirection, child.constraints.growthDirection)) {
case AxisDirection.down:
case AxisDirection.right:
- return parentMainAxisPosition - childParentData.layoutOffset;
+ return parentMainAxisPosition - childParentData.layoutOffset!;
case AxisDirection.up:
- return (size.height - parentMainAxisPosition) - childParentData.layoutOffset;
+ return (size.height - parentMainAxisPosition) - childParentData.layoutOffset!;
case AxisDirection.left:
- return (size.width - parentMainAxisPosition) - childParentData.layoutOffset;
+ return (size.width - parentMainAxisPosition) - childParentData.layoutOffset!;
}
- return 0.0;
}
@override
@@ -1970,7 +1987,7 @@
@override
Iterable<RenderSliver> get childrenInPaintOrder sync* {
- RenderSliver child = firstChild;
+ RenderSliver? child = firstChild;
while (child != null) {
yield child;
child = childAfter(child);
@@ -1979,7 +1996,7 @@
@override
Iterable<RenderSliver> get childrenInHitTestOrder sync* {
- RenderSliver child = lastChild;
+ RenderSliver? child = lastChild;
while (child != null) {
yield child;
child = childBefore(child);
diff --git a/packages/flutter/lib/src/rendering/viewport_offset.dart b/packages/flutter/lib/src/rendering/viewport_offset.dart
index 456b8d5..fae4131 100644
--- a/packages/flutter/lib/src/rendering/viewport_offset.dart
+++ b/packages/flutter/lib/src/rendering/viewport_offset.dart
@@ -2,8 +2,6 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-// @dart = 2.8
-
import 'dart:async';
import 'package:flutter/animation.dart';
@@ -51,7 +49,6 @@
case ScrollDirection.reverse:
return ScrollDirection.forward;
}
- return null;
}
/// Which part of the content inside the viewport should be visible.
@@ -181,8 +178,8 @@
/// animation, use [jumpTo].
Future<void> animateTo(
double to, {
- @required Duration duration,
- @required Curve curve,
+ required Duration duration,
+ required Curve curve,
});
/// Calls [jumpTo] if duration is null or [Duration.zero], otherwise
@@ -194,9 +191,9 @@
/// underscroll.
Future<void> moveTo(
double to, {
- Duration duration,
- Curve curve,
- bool clamp,
+ Duration? duration,
+ Curve? curve,
+ bool? clamp,
}) {
assert(to != null);
if (duration == null || duration == Duration.zero) {
@@ -248,7 +245,7 @@
/// `super.debugFillDescription(description)`.
@mustCallSuper
void debugFillDescription(List<String> description) {
- description.add('offset: ${pixels?.toStringAsFixed(1)}');
+ description.add('offset: ${pixels.toStringAsFixed(1)}');
}
}
@@ -280,8 +277,8 @@
@override
Future<void> animateTo(
double to, {
- @required Duration duration,
- @required Curve curve,
+ required Duration duration,
+ required Curve curve,
}) async { }
@override
diff --git a/packages/flutter/lib/src/rendering/wrap.dart b/packages/flutter/lib/src/rendering/wrap.dart
index 7e3e138..4d9d4a8 100644
--- a/packages/flutter/lib/src/rendering/wrap.dart
+++ b/packages/flutter/lib/src/rendering/wrap.dart
@@ -2,8 +2,6 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-// @dart = 2.8
-
import 'dart:math' as math;
import 'box.dart';
@@ -111,14 +109,14 @@
/// By default, the wrap layout is horizontal and both the children and the
/// runs are aligned to the start.
RenderWrap({
- List<RenderBox> children,
+ List<RenderBox>? children,
Axis direction = Axis.horizontal,
WrapAlignment alignment = WrapAlignment.start,
double spacing = 0.0,
WrapAlignment runAlignment = WrapAlignment.start,
double runSpacing = 0.0,
WrapCrossAlignment crossAxisAlignment = WrapCrossAlignment.start,
- TextDirection textDirection,
+ TextDirection? textDirection,
VerticalDirection verticalDirection = VerticalDirection.down,
Clip clipBehavior = Clip.none,
}) : assert(direction != null),
@@ -292,9 +290,9 @@
/// [crossAxisAlignment] is either [WrapCrossAlignment.start] or
/// [WrapCrossAlignment.end], or there's more than one child, then the
/// [textDirection] must not be null.
- TextDirection get textDirection => _textDirection;
- TextDirection _textDirection;
- set textDirection(TextDirection value) {
+ TextDirection? get textDirection => _textDirection;
+ TextDirection? _textDirection;
+ set textDirection(TextDirection? value) {
if (_textDirection != value) {
_textDirection = value;
markNeedsLayout();
@@ -407,7 +405,7 @@
double runWidth = 0.0;
double runHeight = 0.0;
int childCount = 0;
- RenderBox child = firstChild;
+ RenderBox? child = firstChild;
while (child != null) {
// TODO(chunhtai): use the new intrinsic API to calculate child sizes
// once https://github.com/flutter/flutter/issues/48679 is fixed.
@@ -437,7 +435,7 @@
double runHeight = 0.0;
double runWidth = 0.0;
int childCount = 0;
- RenderBox child = firstChild;
+ RenderBox? child = firstChild;
while (child != null) {
// TODO(chunhtai): use the new intrinsic API to calculate child sizes
// once https://github.com/flutter/flutter/issues/48679 is fixed.
@@ -466,7 +464,7 @@
switch (direction) {
case Axis.horizontal:
double width = 0.0;
- RenderBox child = firstChild;
+ RenderBox? child = firstChild;
while (child != null) {
width = math.max(width, child.getMinIntrinsicWidth(double.infinity));
child = childAfter(child);
@@ -475,7 +473,6 @@
case Axis.vertical:
return _computeIntrinsicWidthForHeight(height);
}
- return null;
}
@override
@@ -483,7 +480,7 @@
switch (direction) {
case Axis.horizontal:
double width = 0.0;
- RenderBox child = firstChild;
+ RenderBox? child = firstChild;
while (child != null) {
width += child.getMaxIntrinsicWidth(double.infinity);
child = childAfter(child);
@@ -492,7 +489,6 @@
case Axis.vertical:
return _computeIntrinsicWidthForHeight(height);
}
- return null;
}
@override
@@ -502,14 +498,13 @@
return _computeIntrinsicHeightForWidth(width);
case Axis.vertical:
double height = 0.0;
- RenderBox child = firstChild;
+ RenderBox? child = firstChild;
while (child != null) {
height = math.max(height, child.getMinIntrinsicHeight(double.infinity));
child = childAfter(child);
}
return height;
}
- return null;
}
@override
@@ -519,18 +514,17 @@
return _computeIntrinsicHeightForWidth(width);
case Axis.vertical:
double height = 0.0;
- RenderBox child = firstChild;
+ RenderBox? child = firstChild;
while (child != null) {
height += child.getMaxIntrinsicHeight(double.infinity);
child = childAfter(child);
}
return height;
}
- return null;
}
@override
- double computeDistanceToActualBaseline(TextBaseline baseline) {
+ double? computeDistanceToActualBaseline(TextBaseline baseline) {
return defaultComputeDistanceToHighestActualBaseline(baseline);
}
@@ -541,7 +535,6 @@
case Axis.vertical:
return child.size.height;
}
- return 0.0;
}
double _getCrossAxisExtent(RenderBox child) {
@@ -551,7 +544,6 @@
case Axis.vertical:
return child.size.width;
}
- return 0.0;
}
Offset _getOffset(double mainAxisOffset, double crossAxisOffset) {
@@ -561,7 +553,6 @@
case Axis.vertical:
return Offset(crossAxisOffset, mainAxisOffset);
}
- return Offset.zero;
}
double _getChildCrossAxisOffset(bool flipCrossAxis, double runCrossAxisExtent, double childCrossAxisExtent) {
@@ -574,7 +565,6 @@
case WrapCrossAlignment.center:
return freeSpace / 2.0;
}
- return 0.0;
}
bool _hasVisualOverflow = false;
@@ -584,7 +574,7 @@
final BoxConstraints constraints = this.constraints;
assert(_debugHasNecessaryDirections);
_hasVisualOverflow = false;
- RenderBox child = firstChild;
+ RenderBox? child = firstChild;
if (child == null) {
size = constraints.smallest;
return;
@@ -765,7 +755,7 @@
}
@override
- bool hitTestChildren(BoxHitTestResult result, { Offset position }) {
+ bool hitTestChildren(BoxHitTestResult result, { required Offset position }) {
return defaultHitTestChildren(result, position: position);
}
diff --git a/packages/flutter/lib/src/services/binding.dart b/packages/flutter/lib/src/services/binding.dart
index d53ff90..cee43a5 100644
--- a/packages/flutter/lib/src/services/binding.dart
+++ b/packages/flutter/lib/src/services/binding.dart
@@ -216,8 +216,8 @@
/// To use a different [RestorationManager] subclasses can override
/// [createRestorationManager], which is called to create the instance
/// returned by this getter.
- RestorationManager get restorationManager => _restorationManager!;
- RestorationManager? _restorationManager;
+ RestorationManager get restorationManager => _restorationManager;
+ late RestorationManager _restorationManager;
/// Creates the [RestorationManager] instance available via
/// [restorationManager].
diff --git a/packages/flutter/lib/src/widgets/framework.dart b/packages/flutter/lib/src/widgets/framework.dart
index 64d42e1..9c2e923 100644
--- a/packages/flutter/lib/src/widgets/framework.dart
+++ b/packages/flutter/lib/src/widgets/framework.dart
@@ -2677,8 +2677,12 @@
e,
stack,
informationCollector: () sync* {
- yield DiagnosticsDebugCreator(DebugCreator(_dirtyElements[index]));
- yield _dirtyElements[index].describeElement('The element being rebuilt at the time was index $index of $dirtyCount');
+ if (index < _dirtyElements.length) {
+ yield DiagnosticsDebugCreator(DebugCreator(_dirtyElements[index]));
+ yield _dirtyElements[index].describeElement('The element being rebuilt at the time was index $index of $dirtyCount');
+ } else {
+ yield ErrorHint('The element being rebuilt at the time was index $index of $dirtyCount, but _dirtyElements only had ${_dirtyElements.length} entries. This suggests some confusion in the framework internals.');
+ }
},
);
}
diff --git a/packages/flutter/lib/src/widgets/table.dart b/packages/flutter/lib/src/widgets/table.dart
index afbfb40..7f7c71a 100644
--- a/packages/flutter/lib/src/widgets/table.dart
+++ b/packages/flutter/lib/src/widgets/table.dart
@@ -201,7 +201,9 @@
/// determine the intrinsic size of the column.
///
/// The keys of this map (column indexes) are zero-based.
- final Map<int, TableColumnWidth> columnWidths;
+ ///
+ /// If this is set to null, then an empty map is assumed.
+ final Map<int, TableColumnWidth>/*?*/ columnWidths;
/// How to determine with widths of columns that don't have an explicit sizing
/// algorithm.
diff --git a/packages/flutter/lib/src/widgets/viewport.dart b/packages/flutter/lib/src/widgets/viewport.dart
index f737994..80275ab 100644
--- a/packages/flutter/lib/src/widgets/viewport.dart
+++ b/packages/flutter/lib/src/widgets/viewport.dart
@@ -51,6 +51,9 @@
/// rebuild this widget when the [offset] changes.
///
/// The [offset] argument must not be null.
+ ///
+ /// The [cacheExtent] must be specified if the [cacheExtentStyle] is
+ /// not [CacheExtentStyle.pixel].
Viewport({
Key key,
this.axisDirection = AxisDirection.down,
@@ -117,6 +120,10 @@
final Key center;
/// {@macro flutter.rendering.viewport.cacheExtent}
+ ///
+ /// See also:
+ ///
+ /// * [cacheExtentStyle], which controls the units of the [cacheExtent].
final double cacheExtent;
/// {@macro flutter.rendering.viewport.cacheExtentStyle}
diff --git a/packages/flutter/lib/src/widgets/widget_inspector.dart b/packages/flutter/lib/src/widgets/widget_inspector.dart
index 8858690..d925380 100644
--- a/packages/flutter/lib/src/widgets/widget_inspector.dart
+++ b/packages/flutter/lib/src/widgets/widget_inspector.dart
@@ -1865,7 +1865,7 @@
void _onPaint(RenderObject renderObject) {
try {
- final Element element = renderObject.debugCreator?.element as Element;
+ final Element element = (renderObject.debugCreator as DebugCreator)?.element;
if (element is! RenderObjectElement) {
// This branch should not hit as long as all RenderObjects were created
// by Widgets. It is possible there might be some render objects
@@ -2363,7 +2363,7 @@
set current(RenderObject value) {
if (_current != value) {
_current = value;
- _currentElement = value.debugCreator.element as Element;
+ _currentElement = (value.debugCreator as DebugCreator).element;
}
}
@@ -2384,7 +2384,7 @@
void _computeCurrent() {
if (_index < candidates.length) {
_current = candidates[index];
- _currentElement = _current.debugCreator.element as Element;
+ _currentElement = (_current.debugCreator as DebugCreator).element;
} else {
_current = null;
_currentElement = null;
diff --git a/packages/flutter/test/rendering/box_test.dart b/packages/flutter/test/rendering/box_test.dart
index ac73edd..aeb83c0 100644
--- a/packages/flutter/test/rendering/box_test.dart
+++ b/packages/flutter/test/rendering/box_test.dart
@@ -394,31 +394,6 @@
{
FlutterError result;
try {
- unconstrained.getMinIntrinsicWidth(null);
- } on FlutterError catch (e) {
- result = e;
- }
- expect(result, isNotNull);
- expect(
- result.toStringDeep(),
- equalsIgnoringHashCodes(
- 'FlutterError\n'
- ' The height argument to getMinIntrinsicWidth was null.\n'
- ' The argument to getMinIntrinsicWidth must not be negative or\n'
- ' null.\n'
- ' If you do not have a specific height in mind, then pass\n'
- ' double.infinity instead.\n'
- ),
- );
- expect(
- result.diagnostics.singleWhere((DiagnosticsNode node) => node.level == DiagnosticLevel.hint).toString(),
- 'If you do not have a specific height in mind, then pass double.infinity instead.',
- );
- }
-
- {
- FlutterError result;
- try {
unconstrained.getMinIntrinsicWidth(-1);
} on FlutterError catch (e) {
result = e;
@@ -447,31 +422,6 @@
{
FlutterError result;
try {
- unconstrained.getMinIntrinsicHeight(null);
- } on FlutterError catch (e) {
- result = e;
- }
- expect(result, isNotNull);
- expect(
- result.toStringDeep(),
- equalsIgnoringHashCodes(
- 'FlutterError\n'
- ' The width argument to getMinIntrinsicHeight was null.\n'
- ' The argument to getMinIntrinsicHeight must not be negative or\n'
- ' null.\n'
- ' If you do not have a specific width in mind, then pass\n'
- ' double.infinity instead.\n'
- ),
- );
- expect(
- result.diagnostics.singleWhere((DiagnosticsNode node) => node.level == DiagnosticLevel.hint).toString(),
- 'If you do not have a specific width in mind, then pass double.infinity instead.',
- );
- }
-
- {
- FlutterError result;
- try {
unconstrained.getMinIntrinsicHeight(-1);
} on FlutterError catch (e) {
result = e;
@@ -500,31 +450,6 @@
{
FlutterError result;
try {
- unconstrained.getMaxIntrinsicWidth(null);
- } on FlutterError catch (e) {
- result = e;
- }
- expect(result, isNotNull);
- expect(
- result.toStringDeep(),
- equalsIgnoringHashCodes(
- 'FlutterError\n'
- ' The height argument to getMaxIntrinsicWidth was null.\n'
- ' The argument to getMaxIntrinsicWidth must not be negative or\n'
- ' null.\n'
- ' If you do not have a specific height in mind, then pass\n'
- ' double.infinity instead.\n'
- ),
- );
- expect(
- result.diagnostics.singleWhere((DiagnosticsNode node) => node.level == DiagnosticLevel.hint).toString(),
- 'If you do not have a specific height in mind, then pass double.infinity instead.',
- );
- }
-
- {
- FlutterError result;
- try {
unconstrained.getMaxIntrinsicWidth(-1);
} on FlutterError catch (e) {
result = e;
@@ -553,31 +478,6 @@
{
FlutterError result;
try {
- unconstrained.getMaxIntrinsicHeight(null);
- } on FlutterError catch (e) {
- result = e;
- }
- expect(result, isNotNull);
- expect(
- result.toStringDeep(),
- equalsIgnoringHashCodes(
- 'FlutterError\n'
- ' The width argument to getMaxIntrinsicHeight was null.\n'
- ' The argument to getMaxIntrinsicHeight must not be negative or\n'
- ' null.\n'
- ' If you do not have a specific width in mind, then pass\n'
- ' double.infinity instead.\n'
- ),
- );
- expect(
- result.diagnostics.singleWhere((DiagnosticsNode node) => node.level == DiagnosticLevel.hint).toString(),
- 'If you do not have a specific width in mind, then pass double.infinity instead.',
- );
- }
-
- {
- FlutterError result;
- try {
unconstrained.getMaxIntrinsicHeight(-1);
} on FlutterError catch (e) {
result = e;
@@ -733,7 +633,7 @@
bool isHit = result.addWithPaintTransform(
transform: null,
- position: null,
+ position: Offset.zero,
hitTest: (BoxHitTestResult result, Offset position) {
expect(result, isNotNull);
positions.add(position);
@@ -741,12 +641,12 @@
},
);
expect(isHit, isTrue);
- expect(positions.single, isNull);
+ expect(positions.single, Offset.zero);
positions.clear();
isHit = result.addWithPaintTransform(
transform: Matrix4.translationValues(20, 30, 0),
- position: null,
+ position: Offset.zero,
hitTest: (BoxHitTestResult result, Offset position) {
expect(result, isNotNull);
positions.add(position);
@@ -754,7 +654,7 @@
},
);
expect(isHit, isTrue);
- expect(positions.single, isNull);
+ expect(positions.single, const Offset(-20.0, -30.0));
positions.clear();
const Offset position = Offset(3, 4);
@@ -817,7 +717,7 @@
bool isHit = result.addWithPaintOffset(
offset: null,
- position: null,
+ position: Offset.zero,
hitTest: (BoxHitTestResult result, Offset position) {
expect(result, isNotNull);
positions.add(position);
@@ -825,12 +725,12 @@
},
);
expect(isHit, isTrue);
- expect(positions.single, isNull);
+ expect(positions.single, Offset.zero);
positions.clear();
isHit = result.addWithPaintOffset(
offset: const Offset(55, 32),
- position: null,
+ position: Offset.zero,
hitTest: (BoxHitTestResult result, Offset position) {
expect(result, isNotNull);
positions.add(position);
@@ -838,7 +738,7 @@
},
);
expect(isHit, isTrue);
- expect(positions.single, isNull);
+ expect(positions.single, const Offset(-55.0, -32.0));
positions.clear();
const Offset position = Offset(3, 4);
@@ -888,7 +788,7 @@
bool isHit = result.addWithRawTransform(
transform: null,
- position: null,
+ position: Offset.zero,
hitTest: (BoxHitTestResult result, Offset position) {
expect(result, isNotNull);
positions.add(position);
@@ -896,12 +796,12 @@
},
);
expect(isHit, isTrue);
- expect(positions.single, isNull);
+ expect(positions.single, Offset.zero);
positions.clear();
isHit = result.addWithRawTransform(
transform: Matrix4.translationValues(20, 30, 0),
- position: null,
+ position: Offset.zero,
hitTest: (BoxHitTestResult result, Offset position) {
expect(result, isNotNull);
positions.add(position);
@@ -909,7 +809,7 @@
},
);
expect(isHit, isTrue);
- expect(positions.single, isNull);
+ expect(positions.single, const Offset(20.0, 30.0));
positions.clear();
const Offset position = Offset(3, 4);
@@ -953,6 +853,82 @@
positions.clear();
});
+ test('addWithOutOfBandPosition', () {
+ final BoxHitTestResult result = BoxHitTestResult();
+ bool ran = false;
+
+ bool isHit = result.addWithOutOfBandPosition(
+ paintOffset: const Offset(20, 30),
+ hitTest: (BoxHitTestResult result) {
+ expect(result, isNotNull);
+ ran = true;
+ return true;
+ },
+ );
+ expect(isHit, isTrue);
+ expect(ran, isTrue);
+ ran = false;
+
+ isHit = result.addWithOutOfBandPosition(
+ paintTransform: Matrix4.translationValues(20, 30, 0),
+ hitTest: (BoxHitTestResult result) {
+ expect(result, isNotNull);
+ ran = true;
+ return true;
+ },
+ );
+ expect(isHit, isTrue);
+ expect(ran, isTrue);
+ ran = false;
+
+ isHit = result.addWithOutOfBandPosition(
+ rawTransform: Matrix4.translationValues(20, 30, 0),
+ hitTest: (BoxHitTestResult result) {
+ expect(result, isNotNull);
+ ran = true;
+ return true;
+ },
+ );
+ expect(isHit, isTrue);
+ expect(ran, isTrue);
+ ran = false;
+
+ isHit = result.addWithOutOfBandPosition(
+ rawTransform: MatrixUtils.forceToPoint(Offset.zero), // cannot be inverted
+ hitTest: (BoxHitTestResult result) {
+ expect(result, isNotNull);
+ ran = true;
+ return true;
+ },
+ );
+ expect(isHit, isTrue);
+ expect(ran, isTrue);
+ ran = false;
+
+ try {
+ isHit = result.addWithOutOfBandPosition(
+ paintTransform: MatrixUtils.forceToPoint(Offset.zero), // cannot be inverted
+ hitTest: (BoxHitTestResult result) {
+ fail('non-invertible transform should be caught');
+ },
+ );
+ fail('no exception thrown');
+ } on AssertionError catch (e) {
+ expect(e.message, 'paintTransform must be invertible.');
+ }
+
+ try {
+ isHit = result.addWithOutOfBandPosition(
+ hitTest: (BoxHitTestResult result) {
+ fail('addWithOutOfBandPosition should need some transformation of some sort');
+ },
+ );
+ fail('no exception thrown');
+ } on AssertionError catch (e) {
+ expect(e.message, 'Exactly one transform or offset argument must be provided.');
+ }
+ });
+
test('error message', () {
{
final RenderBox renderObject = RenderConstrainedBox(
diff --git a/packages/flutter/test/rendering/independent_layout_test.dart b/packages/flutter/test/rendering/independent_layout_test.dart
index c2bba73..40a7a21 100644
--- a/packages/flutter/test/rendering/independent_layout_test.dart
+++ b/packages/flutter/test/rendering/independent_layout_test.dart
@@ -4,6 +4,8 @@
// @dart = 2.8
+import 'dart:ui' as ui show window;
+
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import '../flutter_test_alternative.dart';
@@ -46,7 +48,7 @@
expect(offscreen.child.hasSize, isFalse);
expect(offscreen.painted, isFalse);
// Attach the offscreen to a custom render view and owner
- final RenderView renderView = RenderView(configuration: testConfiguration, window: null);
+ final RenderView renderView = RenderView(configuration: testConfiguration, window: ui.window);
final PipelineOwner pipelineOwner = PipelineOwner();
renderView.attach(pipelineOwner);
renderView.child = offscreen.root;
@@ -76,7 +78,7 @@
expect(offscreen.child.hasSize, isFalse);
expect(offscreen.painted, isFalse);
// Attach the offscreen to a custom render view and owner
- final RenderView renderView = RenderView(configuration: testConfiguration, window: null);
+ final RenderView renderView = RenderView(configuration: testConfiguration, window: ui.window);
final PipelineOwner pipelineOwner = PipelineOwner();
renderView.attach(pipelineOwner);
renderView.child = offscreen.root;
diff --git a/packages/flutter/test/rendering/mouse_tracking_cursor_test.dart b/packages/flutter/test/rendering/mouse_tracking_cursor_test.dart
index e68f99d..46f7084 100644
--- a/packages/flutter/test/rendering/mouse_tracking_cursor_test.dart
+++ b/packages/flutter/test/rendering/mouse_tracking_cursor_test.dart
@@ -47,7 +47,7 @@
for (final HitTestTarget target in annotationFinder(position)) {
result.addWithRawTransform(
transform: Matrix4.identity(),
- position: null,
+ position: position,
hitTest: (BoxHitTestResult result, Offset position) {
result.add(HitTestEntry(target));
return true;
diff --git a/packages/flutter/test/rendering/mouse_tracking_test.dart b/packages/flutter/test/rendering/mouse_tracking_test.dart
index 8a5105d..956f89b 100644
--- a/packages/flutter/test/rendering/mouse_tracking_test.dart
+++ b/packages/flutter/test/rendering/mouse_tracking_test.dart
@@ -32,7 +32,7 @@
for (final TestAnnotationEntry entry in annotationFinder(position)) {
result.addWithRawTransform(
transform: entry.transform,
- position: null,
+ position: position,
hitTest: (BoxHitTestResult result, Offset position) {
result.add(entry);
return true;
diff --git a/packages/flutter/test/rendering/proxy_box_test.dart b/packages/flutter/test/rendering/proxy_box_test.dart
index 3f1e91e..c7d501b 100644
--- a/packages/flutter/test/rendering/proxy_box_test.dart
+++ b/packages/flutter/test/rendering/proxy_box_test.dart
@@ -30,7 +30,7 @@
expect(transform, Matrix4.zero());
final BoxHitTestResult hitTestResult = BoxHitTestResult();
- expect(fittedBox.hitTestChildren(hitTestResult), isFalse);
+ expect(fittedBox.hitTestChildren(hitTestResult, position: Offset.zero), isFalse);
});
test('RenderFittedBox does not paint with empty sizes', () {
diff --git a/packages/flutter/test/rendering/slivers_block_test.dart b/packages/flutter/test/rendering/slivers_block_test.dart
index 985914d..05bb823 100644
--- a/packages/flutter/test/rendering/slivers_block_test.dart
+++ b/packages/flutter/test/rendering/slivers_block_test.dart
@@ -343,8 +343,6 @@
expect(candidate.keepAlive, isFalse);
expect(candidate.index, isNull);
expect(candidate.toString(), 'index=null; layoutOffset=None');
- candidate.keepAlive = null;
- expect(candidate.toString(), 'index=null; layoutOffset=None');
candidate.keepAlive = true;
expect(candidate.toString(), 'index=null; keepAlive; layoutOffset=None');
candidate.keepAlive = false;
diff --git a/packages/flutter/test/widgets/custom_multi_child_layout_test.dart b/packages/flutter/test/widgets/custom_multi_child_layout_test.dart
index 476daf2..0a120bd 100644
--- a/packages/flutter/test/widgets/custom_multi_child_layout_test.dart
+++ b/packages/flutter/test/widgets/custom_multi_child_layout_test.dart
@@ -134,18 +134,6 @@
bool shouldRelayout(MultiChildLayoutDelegate oldDelegate) => true;
}
-// Used in the 'performLayout error control test' test case
-// to trigger an error when positioning with null offset
-class NullOffsetPositionDelegate extends MultiChildLayoutDelegate {
- @override
- void performLayout(Size size) {
- positionChild(0, null);
- }
-
- @override
- bool shouldRelayout(MultiChildLayoutDelegate oldDelegate) => true;
-}
-
// Used in the 'performLayout error control test' test case for triggering
// to layout child more than once
class InvalidConstraintsChildLayoutDelegate extends MultiChildLayoutDelegate {
@@ -371,17 +359,6 @@
);
});
- testWidgets('positionChild on non existent child', (WidgetTester tester) async {
- expectFlutterErrorMessage(
- tester: tester,
- delegate: NullOffsetPositionDelegate(),
- message:
- 'FlutterError\n'
- ' The NullOffsetPositionDelegate custom multichild layout delegate\n'
- ' provided a null position for the child with id "0".\n',
- );
- });
-
testWidgets("_callPerformLayout on child that doesn't have id", (WidgetTester tester) async {
expectFlutterErrorMessage(
widget: Center(
diff --git a/packages/flutter/test/widgets/custom_paint_test.dart b/packages/flutter/test/widgets/custom_paint_test.dart
index dd4eb5e..c162a54 100644
--- a/packages/flutter/test/widgets/custom_paint_test.dart
+++ b/packages/flutter/test/widgets/custom_paint_test.dart
@@ -138,48 +138,6 @@
expect(error.toStringDeep(), contains('2 more times'));
});
- testWidgets('assembleSemanticsNode throws FlutterError', (WidgetTester tester) async {
- final List<String> log = <String>[];
- final GlobalKey target = GlobalKey();
- await tester.pumpWidget(CustomPaint(
- key: target,
- isComplex: true,
- painter: TestCustomPainter(log: log),
- ));
- final RenderCustomPaint renderCustom = target.currentContext.findRenderObject() as RenderCustomPaint;
- dynamic error;
- try {
- renderCustom.assembleSemanticsNode(
- null,
- null,
- <SemanticsNode>[SemanticsNode()],
- );
- } on FlutterError catch (e) {
- error = e;
- }
- expect(error, isNotNull);
- expect(error.toStringDeep(), equalsIgnoringHashCodes(
- 'FlutterError\n'
- ' RenderCustomPaint does not have a child widget but received a\n'
- ' non-empty list of child SemanticsNode:\n'
- ' SemanticsNode#1(Rect.fromLTRB(0.0, 0.0, 0.0, 0.0), invisible)\n'
- ));
-
- await tester.pumpWidget(CustomPaint(
- key: target,
- isComplex: true,
- painter: TestCustomPainterWithCustomSemanticsBuilder(),
- ));
- final dynamic exception = tester.takeException();
- expect(exception, isFlutterError);
- error = exception;
- expect(error.toStringDeep(), equalsIgnoringHashCodes(
- 'FlutterError\n'
- ' Failed to update the list of CustomPainterSemantics:\n'
- " - duplicate key [<'0'>] found at position 1\n"
- ));
- });
-
testWidgets('CustomPaint sizing', (WidgetTester tester) async {
final GlobalKey target = GlobalKey();
diff --git a/packages/flutter/test/widgets/root_restoration_scope_test.dart b/packages/flutter/test/widgets/root_restoration_scope_test.dart
index a996589..32dc1a1 100644
--- a/packages/flutter/test/widgets/root_restoration_scope_test.dart
+++ b/packages/flutter/test/widgets/root_restoration_scope_test.dart
@@ -379,7 +379,7 @@
@override
TestRestorationManager createRestorationManager() {
- return null;
+ return TestRestorationManager();
}
int _deferred = 0;
diff --git a/packages/flutter/test/widgets/widget_inspector_test.dart b/packages/flutter/test/widgets/widget_inspector_test.dart
index 5701f47..afc644a 100644
--- a/packages/flutter/test/widgets/widget_inspector_test.dart
+++ b/packages/flutter/test/widgets/widget_inspector_test.dart
@@ -745,7 +745,7 @@
service.setSelection(elementB.renderObject);
expect(selectionChangedCount, equals(2));
expect(service.selection.current, equals(elementB.renderObject));
- expect(service.selection.currentElement, equals(elementB.renderObject.debugCreator.element));
+ expect(service.selection.currentElement, equals((elementB.renderObject.debugCreator as DebugCreator).element));
service.setSelection('invalid selection');
expect(selectionChangedCount, equals(2));
@@ -1186,7 +1186,7 @@
service.setSelection(elementB.renderObject);
expect(selectionChangedCount, equals(2));
expect(service.selection.current, equals(elementB.renderObject));
- expect(service.selection.currentElement, equals(elementB.renderObject.debugCreator.element));
+ expect(service.selection.currentElement, equals((elementB.renderObject.debugCreator as DebugCreator).element));
service.setSelection('invalid selection');
expect(selectionChangedCount, equals(2));
diff --git a/packages/flutter_test/lib/src/controller.dart b/packages/flutter_test/lib/src/controller.dart
index 0e3571d..3cc2920 100644
--- a/packages/flutter_test/lib/src/controller.dart
+++ b/packages/flutter_test/lib/src/controller.dart
@@ -759,6 +759,7 @@
PointerDeviceKind kind = PointerDeviceKind.touch,
int buttons = kPrimaryButton,
}) async {
+ assert(downLocation != null);
final TestGesture result = await createGesture(
pointer: pointer,
kind: kind,
diff --git a/packages/flutter_test/lib/src/widget_tester.dart b/packages/flutter_test/lib/src/widget_tester.dart
index c0cea08..06856c1 100644
--- a/packages/flutter_test/lib/src/widget_tester.dart
+++ b/packages/flutter_test/lib/src/widget_tester.dart
@@ -818,6 +818,7 @@
@override
HitTestResult hitTestOnBinding(Offset location) {
+ assert(location != null);
location = binding.localToGlobal(location);
return super.hitTestOnBinding(location);
}