diff --git a/packages/flutter/lib/src/cupertino/text_field.dart b/packages/flutter/lib/src/cupertino/text_field.dart index 308f893c28..cafa9b0372 100644 --- a/packages/flutter/lib/src/cupertino/text_field.dart +++ b/packages/flutter/lib/src/cupertino/text_field.dart @@ -591,7 +591,7 @@ class CupertinoTextField extends StatefulWidget { /// {@macro flutter.widgets.editableText.scrollPhysics} final ScrollPhysics scrollPhysics; - /// {@macro flutter.rendering.editable.selectionEnabled} + /// {@macro flutter.widgets.editableText.selectionEnabled} bool get selectionEnabled => enableInteractiveSelection; /// {@macro flutter.material.textfield.onTap} diff --git a/packages/flutter/lib/src/material/selectable_text.dart b/packages/flutter/lib/src/material/selectable_text.dart index be77133753..a97353a287 100644 --- a/packages/flutter/lib/src/material/selectable_text.dart +++ b/packages/flutter/lib/src/material/selectable_text.dart @@ -391,11 +391,8 @@ class SelectableText extends StatefulWidget { /// If not set, select all and copy will be enabled by default. final ToolbarOptions toolbarOptions; - /// True if interactive selection is enabled based on the values of - /// [enableInteractiveSelection]. - bool get selectionEnabled { - return enableInteractiveSelection; - } + /// {@macro flutter.widgets.editableText.selectionEnabled} + bool get selectionEnabled => enableInteractiveSelection; /// Called when the user taps on this selectable text. /// diff --git a/packages/flutter/lib/src/material/text_field.dart b/packages/flutter/lib/src/material/text_field.dart index f50f24a3b6..ad47cb4dd5 100644 --- a/packages/flutter/lib/src/material/text_field.dart +++ b/packages/flutter/lib/src/material/text_field.dart @@ -702,7 +702,7 @@ class TextField extends StatefulWidget { /// {@macro flutter.widgets.scrollable.dragStartBehavior} final DragStartBehavior dragStartBehavior; - /// {@macro flutter.rendering.editable.selectionEnabled} + /// {@macro flutter.widgets.editableText.selectionEnabled} bool get selectionEnabled => enableInteractiveSelection; /// {@template flutter.material.textfield.onTap} diff --git a/packages/flutter/lib/src/painting/text_painter.dart b/packages/flutter/lib/src/painting/text_painter.dart index 1c26957c02..82713fb9ca 100644 --- a/packages/flutter/lib/src/painting/text_painter.dart +++ b/packages/flutter/lib/src/painting/text_painter.dart @@ -2,7 +2,6 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. - import 'dart:math' show min, max; import 'dart:ui' as ui show Paragraph, ParagraphBuilder, ParagraphConstraints, ParagraphStyle, PlaceholderAlignment, LineMetrics, TextHeightBehavior, BoxHeightStyle, BoxWidthStyle; diff --git a/packages/flutter/lib/src/rendering/box.dart b/packages/flutter/lib/src/rendering/box.dart index 6ddcda8f71..46d646eb34 100644 --- a/packages/flutter/lib/src/rendering/box.dart +++ b/packages/flutter/lib/src/rendering/box.dart @@ -19,7 +19,7 @@ import 'object.dart'; 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. @@ -92,10 +92,10 @@ class BoxConstraints extends Constraints { this.maxWidth = double.infinity, this.minHeight = 0.0, this.maxHeight = double.infinity, - }) : assert (minWidth != null), - assert (maxWidth != null), - assert (minHeight != null), - assert (maxHeight != null); + }) : assert(minWidth != null), + assert(maxWidth != null), + assert(minHeight != null), + assert(maxHeight != null); /// Creates box constraints that is respected only by the given size. BoxConstraints.tight(Size size) @@ -468,7 +468,7 @@ class BoxConstraints extends Constraints { /// 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; @@ -1294,9 +1294,9 @@ abstract class RenderBox extends RenderObject { 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(() { @@ -1332,7 +1332,7 @@ abstract class RenderBox extends RenderObject { /// /// Do not override this method. Instead, implement [computeMinIntrinsicWidth]. @mustCallSuper - double getMinIntrinsicWidth(double height) { + double getMinIntrinsicWidth(double/*!*/ height) { assert(() { if (height == null) { throw FlutterError.fromParts([ @@ -1455,7 +1455,7 @@ abstract class RenderBox extends RenderObject { /// * [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,7 +1477,7 @@ abstract class RenderBox extends RenderObject { /// Do not override this method. Instead, implement /// [computeMaxIntrinsicWidth]. @mustCallSuper - double getMaxIntrinsicWidth(double height) { + double getMaxIntrinsicWidth(double/*!*/ height) { assert(() { if (height == null) { throw FlutterError.fromParts([ @@ -1535,7 +1535,7 @@ abstract class RenderBox extends RenderObject { /// /// * [computeMinIntrinsicWidth], which has usage examples. @protected - double computeMaxIntrinsicWidth(double height) { + double/*!*/ computeMaxIntrinsicWidth(double/*!*/ height) { return 0.0; } @@ -1556,7 +1556,7 @@ abstract class RenderBox extends RenderObject { /// Do not override this method. Instead, implement /// [computeMinIntrinsicHeight]. @mustCallSuper - double getMinIntrinsicHeight(double width) { + double getMinIntrinsicHeight(double/*!*/ width) { assert(() { if (width == null) { throw FlutterError.fromParts([ @@ -1612,7 +1612,7 @@ abstract class RenderBox extends RenderObject { /// * [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,7 +1634,7 @@ abstract class RenderBox extends RenderObject { /// Do not override this method. Instead, implement /// [computeMaxIntrinsicHeight]. @mustCallSuper - double getMaxIntrinsicHeight(double width) { + double getMaxIntrinsicHeight(double/*!*/ width) { assert(() { if (width == null) { throw FlutterError.fromParts([ @@ -1692,7 +1692,7 @@ abstract class RenderBox extends RenderObject { /// /// * [computeMinIntrinsicWidth], which has usage examples. @protected - double computeMaxIntrinsicHeight(double width) { + double/*!*/ computeMaxIntrinsicHeight(double/*!*/ width) { return 0.0; } @@ -1709,7 +1709,7 @@ abstract class RenderBox extends RenderObject { /// [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; @@ -1733,12 +1733,12 @@ abstract class RenderBox extends RenderObject { }()); return _size; } - Size _size; + /*late*/ 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(() { @@ -1852,7 +1852,7 @@ abstract class RenderBox extends RenderObject { size = size; } - Map _cachedBaselines; + Map _cachedBaselines; static bool _debugDoingBaseline = false; static bool _debugSetDoingBaseline(bool value) { _debugDoingBaseline = value; @@ -1875,7 +1875,7 @@ abstract class RenderBox extends RenderObject { /// /// 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(() { @@ -1903,7 +1903,7 @@ abstract class RenderBox extends RenderObject { /// 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 ??= {}; _cachedBaselines.putIfAbsent(baseline, () => computeDistanceToActualBaseline(baseline)); diff --git a/packages/flutter/lib/src/rendering/custom_layout.dart b/packages/flutter/lib/src/rendering/custom_layout.dart index b650b636e4..22ff89cf56 100644 --- a/packages/flutter/lib/src/rendering/custom_layout.dart +++ b/packages/flutter/lib/src/rendering/custom_layout.dart @@ -124,8 +124,9 @@ abstract class MultiChildLayoutDelegate { final Listenable _relayout; - Map _idToChild; - Set _debugChildrenNeedingLayout; + // TODO(ianh): make these late final + /*late*/ Map/*!*/ _idToChild; + /*late*/ Set/*!*/ _debugChildrenNeedingLayout; /// True if a non-null LayoutChild was provided for the specified id. /// @@ -140,7 +141,7 @@ abstract class MultiChildLayoutDelegate { /// 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) { + Size/*!*/ layoutChild(Object childId, BoxConstraints constraints) { final RenderBox child = _idToChild[childId]; assert(() { if (child == null) { @@ -211,7 +212,8 @@ abstract class MultiChildLayoutDelegate { // we return. final Map previousIdToChild = _idToChild; - Set debugPreviousChildrenNeedingLayout; + // TODO(ianh): make the next line final + /*late*/ Set/*!*/ debugPreviousChildrenNeedingLayout; assert(() { debugPreviousChildrenNeedingLayout = _debugChildrenNeedingLayout; _debugChildrenNeedingLayout = {}; diff --git a/packages/flutter/lib/src/rendering/custom_paint.dart b/packages/flutter/lib/src/rendering/custom_paint.dart index 197de08c2b..241fe4f4ee 100644 --- a/packages/flutter/lib/src/rendering/custom_paint.dart +++ b/packages/flutter/lib/src/rendering/custom_paint.dart @@ -521,8 +521,9 @@ class RenderCustomPaint extends RenderProxyBox { markNeedsSemanticsUpdate(); } - void _paintWithPainter(Canvas canvas, Offset offset, CustomPainter painter) { - int debugPreviousCanvasSaveCount; + void _paintWithPainter(Canvas canvas, Offset offset, CustomPainter/*!*/ painter) { + // TODO(ianh): make the next line final + /*late*/ int/*!*/ debugPreviousCanvasSaveCount; canvas.save(); assert(() { debugPreviousCanvasSaveCount = canvas.getSaveCount(); @@ -603,10 +604,10 @@ class RenderCustomPaint extends RenderProxyBox { } /// Describe the semantics of the picture painted by the [painter]. - List _backgroundSemanticsNodes; + List _backgroundSemanticsNodes; /// Describe the semantics of the picture painted by the [foregroundPainter]. - List _foregroundSemanticsNodes; + List _foregroundSemanticsNodes; @override void assembleSemanticsNode( @@ -675,7 +676,7 @@ class RenderCustomPaint extends RenderProxyBox { /// 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 _updateSemanticsChildren( + static List _updateSemanticsChildren( List oldSemantics, List newChildSemantics, ) { @@ -683,7 +684,7 @@ class RenderCustomPaint extends RenderProxyBox { newChildSemantics = newChildSemantics ?? const []; assert(() { - final Map keys = HashMap(); + final Map keys = HashMap(); final List information = []; for (int i = 0; i < newChildSemantics.length; i += 1) { final CustomPainterSemantics child = newChildSemantics[i]; @@ -708,7 +709,7 @@ class RenderCustomPaint extends RenderProxyBox { int newChildrenBottom = newChildSemantics.length - 1; int oldChildrenBottom = oldSemantics.length - 1; - final List newChildren = List(newChildSemantics.length); + final List newChildren = List(newChildSemantics.length); // Update the top of the list. while ((oldChildrenTop <= oldChildrenBottom) && (newChildrenTop <= newChildrenBottom)) { @@ -734,7 +735,7 @@ class RenderCustomPaint extends RenderProxyBox { // Scan the old children in the middle of the list. final bool haveOldChildren = oldChildrenTop <= oldChildrenBottom; - Map oldKeyedChildren; + Map oldKeyedChildren; if (haveOldChildren) { oldKeyedChildren = {}; while (oldChildrenTop <= oldChildrenBottom) { diff --git a/packages/flutter/lib/src/rendering/debug.dart b/packages/flutter/lib/src/rendering/debug.dart index fab2111071..1208258e8e 100644 --- a/packages/flutter/lib/src/rendering/debug.dart +++ b/packages/flutter/lib/src/rendering/debug.dart @@ -174,7 +174,7 @@ bool debugProfileLayoutsEnabled = false; 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. /// diff --git a/packages/flutter/lib/src/rendering/editable.dart b/packages/flutter/lib/src/rendering/editable.dart index 73cbaccf8d..62d67bb4fc 100644 --- a/packages/flutter/lib/src/rendering/editable.dart +++ b/packages/flutter/lib/src/rendering/editable.dart @@ -412,10 +412,11 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin { final ValueNotifier _selectionEndInViewport = ValueNotifier(true); void _updateSelectionExtentsVisibility(Offset effectiveOffset) { + assert(selection != null); 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 @@ -431,7 +432,7 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin { .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 @@ -462,12 +463,8 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin { // components, so always send those events, even if we didn't think it // changed. Also, focusing an empty field is sent as a selection change even // if the selection offset didn't change. - final bool focusingEmpty = nextSelection.baseOffset == 0 - && nextSelection.extentOffset == 0 - && !hasFocus; - if (nextSelection == selection - && cause != SelectionChangedCause.keyboard - && !focusingEmpty) { + final bool focusingEmpty = nextSelection.baseOffset == 0 && nextSelection.extentOffset == 0 && !hasFocus; + if (nextSelection == selection && cause != SelectionChangedCause.keyboard && !focusingEmpty) { return; } if (onSelectionChanged != null) { @@ -514,7 +511,7 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin { }; void _handleKeyEvent(RawKeyEvent keyEvent) { - if(kIsWeb) { + if (kIsWeb) { // On web platform, we should ignore the key because it's processed already. return; } @@ -534,6 +531,10 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin { return; } + // TODO(ianh): It seems to be entirely possible for the selection to be null here, but + // all the keyboard handling functions assume it is not. + assert(selection != null); + final bool isWordModifierPressed = isMacOS ? keyEvent.isAltPressed : keyEvent.isControlPressed; final bool isLineModifierPressed = isMacOS ? keyEvent.isMetaPressed : keyEvent.isAltPressed; final bool isShortcutModifierPressed = isMacOS ? keyEvent.isMetaPressed : keyEvent.isControlPressed; @@ -614,17 +615,18 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin { } void _handleMovement( - LogicalKeyboardKey key, { - @required bool wordModifier, - @required bool lineModifier, - @required bool shift, - }) { + LogicalKeyboardKey key, { + @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; @@ -753,6 +755,7 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin { // Handles shortcut functionality including cut, copy, paste and select all // using control/command + (X, C, V, A). Future _handleShortcuts(LogicalKeyboardKey key) async { + assert(selection != null); assert(_shortcutKeys.contains(key), 'shortcut key $key not recognized.'); if (key == LogicalKeyboardKey.keyC) { if (!selection.isCollapsed) { @@ -802,6 +805,7 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin { } void _handleDelete() { + assert(_selection != null); final String textAfter = selection.textAfter(_plainText); if (textAfter.isNotEmpty) { final int deleteCount = nextCharacter(0, textAfter); @@ -839,7 +843,7 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin { // Returns a cached plain text version of the text in the painter. String _cachedPlainText; - String get _plainText { + String/*!*/ get _plainText { _cachedPlainText ??= _textPainter.text.toPlainText(); return _cachedPlainText; } @@ -847,7 +851,7 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin { /// The text to display. 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; @@ -881,7 +885,10 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin { /// its left. /// /// This must not be null. - TextDirection get textDirection => _textPainter.textDirection; + // 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/*!*/; set textDirection(TextDirection value) { assert(value != null); if (_textPainter.textDirection == value) @@ -1070,6 +1077,11 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin { List _selectionRects; /// The region of text that is selected, if any. + /// + /// The caret position is represented by a collapsed selection. + /// + /// 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) { @@ -1231,13 +1243,22 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin { markNeedsPaint(); } - /// If false, [describeSemanticsConfiguration] will not set the - /// configuration's cursor motion or set selection callbacks. + /// Whether to allow the user to change the selection. /// - /// True by default. + /// Since [RenderEditable] does not handle selection manipulation + /// itself, this actually only affects whether the accessibility + /// hints provided to the system (via + /// [describeSemanticsConfiguration]) will enable selection + /// manipulation. It's the responsibility of this object's owner + /// to provide selection manipulation affordances. + /// + /// This field is used by [selectionEnabled] (which then controls + /// 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) { + set enableInteractiveSelection(bool/*?*/ value) { if (_enableInteractiveSelection == value) return; _enableInteractiveSelection = value; @@ -1245,18 +1266,26 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin { markNeedsSemanticsUpdate(); } - /// {@template flutter.rendering.editable.selectionEnabled} - /// True if interactive selection is enabled based on the values of + /// Whether interactive selection are enabled based on the values of /// [enableInteractiveSelection] and [obscureText]. /// - /// By default [enableInteractiveSelection] is null, obscureText is false, - /// and this method returns true. - /// If [enableInteractiveSelection] is null and obscureText is true, then this - /// method returns false. This is the common case for password fields. - /// If [enableInteractiveSelection] is non-null then its value is returned. An - /// app might set it to true to enable interactive selection for a password - /// field, or to false to unconditionally disable interactive selection. - /// {@endtemplate} + /// Since [RenderEditable] does not handle selection manipulation + /// itself, this actually only affects whether the accessibility + /// hints provided to the system (via + /// [describeSemanticsConfiguration]) will enable selection + /// manipulation. It's the responsibility of this object's owner + /// to provide selection manipulation affordances. + /// + /// By default, [enableInteractiveSelection] is null, [obscureText] is false, + /// and this getter returns true. + /// + /// If [enableInteractiveSelection] is null and [obscureText] is true, then this + /// getter returns false. This is the common case for password fields. + /// + /// If [enableInteractiveSelection] is non-null then its value is + /// returned. An application might [enableInteractiveSelection] to + /// true to enable interactive selection for a password field, or to + /// false to unconditionally disable interactive selection. bool get selectionEnabled { return enableInteractiveSelection ?? !obscureText; } @@ -1264,9 +1293,12 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin { /// The color used to paint the prompt rectangle. /// /// The prompt rectangle will only be requested on non-web iOS applications. - Color get promptRectColor => _promptRectPaint.color; - set promptRectColor(Color newValue) { - // Painter.color can not be null. + // 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) { + // Painter.color cannot be null. if (newValue == null) { setPromptRectRange(null); return; @@ -1287,7 +1319,7 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin { /// 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; @@ -1301,7 +1333,7 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin { /// 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; @@ -1337,14 +1369,14 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin { if (hasFocus && selectionEnabled) config.onSetSelection = _handleSetSelection; - if (selectionEnabled && _selection?.isValid == true) { - config.textSelection = _selection; - if (_textPainter.getOffsetBefore(_selection.extentOffset) != null) { + if (selectionEnabled && selection?.isValid == true) { + config.textSelection = selection; + 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; @@ -1352,38 +1384,45 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin { } } + // TODO(ianh): in theory, [selection] could become null between when + // we last called describeSemanticsConfiguration and when the + // callbacks are invoked, in which case the callbacks will crash... + void _handleSetSelection(TextSelection selection) { _handleSelectionChange(selection, SelectionChangedCause.keyboard); } void _handleMoveCursorForwardByCharacter(bool extentSelection) { - final int extentOffset = _textPainter.getOffsetAfter(_selection.extentOffset); + assert(selection != null); + 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, ); } void _handleMoveCursorBackwardByCharacter(bool extentSelection) { - final int extentOffset = _textPainter.getOffsetBefore(_selection.extentOffset); + assert(selection != null); + 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, ); } void _handleMoveCursorForwardByWord(bool extentSelection) { - final TextRange currentWord = _textPainter.getWordBoundary(_selection.extent); + assert(selection != null); + final TextRange currentWord = _textPainter.getWordBoundary(selection.extent); if (currentWord == null) return; 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, @@ -1394,13 +1433,14 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin { } void _handleMoveCursorBackwardByWord(bool extentSelection) { - final TextRange currentWord = _textPainter.getWordBoundary(_selection.extent); + assert(selection != null); + final TextRange currentWord = _textPainter.getWordBoundary(selection.extent); if (currentWord == null) return; 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, @@ -1441,7 +1481,7 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin { // 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; } @@ -1475,7 +1515,7 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin { 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); @@ -1485,7 +1525,7 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin { return null; } - double get _viewportExtent { + double/*!*/ get _viewportExtent { assert(hasSize); switch (_viewportAxis) { case Axis.horizontal: @@ -1496,7 +1536,7 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin { return null; } - double _getMaxScrollExtent(Size contentSize) { + double/*!*/ _getMaxScrollExtent(Size contentSize) { assert(hasSize); switch (_viewportAxis) { case Axis.horizontal: @@ -1866,8 +1906,6 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin { return TextSelection(baseOffset: line.start, extentOffset: line.end); } - Rect _caretPrototype; - void _layoutText({ double minWidth = 0.0, double maxWidth = double.infinity }) { assert(maxWidth != null && minWidth != null); if (_textLayoutLastMaxWidth == maxWidth && _textLayoutLastMinWidth == minWidth) @@ -1884,6 +1922,8 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin { _textLayoutLastMaxWidth = maxWidth; } + /*late*/ Rect _caretPrototype; + // TODO(garyq): This is no longer producing the highest-fidelity caret // heights for Android, especially when non-alphabetic languages // are involved. The current implementation overrides the height set @@ -1895,25 +1935,27 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin { /// On iOS, the cursor is taller than the cursor on Android. The height /// of the cursor for iOS is approximate and obtained through an eyeball /// comparison. - Rect get _getCaretPrototype { + void _computeCaretPrototype() { assert(defaultTargetPlatform != null); switch (defaultTargetPlatform) { case TargetPlatform.iOS: case TargetPlatform.macOS: - return Rect.fromLTWH(0.0, 0.0, cursorWidth, cursorHeight + 2); + _caretPrototype = Rect.fromLTWH(0.0, 0.0, cursorWidth, cursorHeight + 2); + break; case TargetPlatform.android: case TargetPlatform.fuchsia: case TargetPlatform.linux: case TargetPlatform.windows: - return Rect.fromLTWH(0.0, _kCaretHeightOffset, cursorWidth, cursorHeight - 2.0 * _kCaretHeightOffset); + _caretPrototype = Rect.fromLTWH(0.0, _kCaretHeightOffset, cursorWidth, cursorHeight - 2.0 * _kCaretHeightOffset); + break; } - return null; } + @override void performLayout() { final BoxConstraints constraints = this.constraints; _layoutText(minWidth: constraints.minWidth, maxWidth: constraints.maxWidth); - _caretPrototype = _getCaretPrototype; + _computeCaretPrototype(); _selectionRects = null; // We grab _textPainter.size here because assigning to `size` on the next // line will trigger us to validate our intrinsic sizes, which will change @@ -1949,6 +1991,7 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin { assert(_textLayoutLastMaxWidth == constraints.maxWidth && _textLayoutLastMinWidth == constraints.minWidth, 'Last width ($_textLayoutLastMinWidth, $_textLayoutLastMaxWidth) not the same as max width constraint (${constraints.minWidth}, ${constraints.maxWidth}).'); + assert(_caretPrototype != null); // If the floating cursor is enabled, the text cursor's color is [backgroundCursorColor] while // the floating cursor's color is _cursorColor; @@ -1979,7 +2022,7 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin { case TargetPlatform.windows: // Override the height to take the full height of the glyph at the TextPosition // when not on iOS. iOS has special handling that creates a taller caret. - // TODO(garyq): See the TODO for _getCaretPrototype. + // TODO(garyq): See the TODO for _computeCaretPrototype(). caretRect = Rect.fromLTWH( caretRect.left, caretRect.top - _kCaretHeightOffset, @@ -2038,8 +2081,8 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin { // We always want the floating cursor to render at full opacity. 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); @@ -2155,16 +2198,17 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin { bool showSelection = false; bool showCaret = false; - if (_selection != null && !_floatingCursorOn) { - if (_selection.isCollapsed && _showCursor.value && cursorColor != null) + if (selection != null && !_floatingCursorOn) { + 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) { - _selectionRects ??= _textPainter.getBoxesForSelection(_selection, boxHeightStyle: _selectionHeightStyle, boxWidthStyle: _selectionWidthStyle); + assert(selection != null); + _selectionRects ??= _textPainter.getBoxesForSelection(selection, boxHeightStyle: _selectionHeightStyle, boxWidthStyle: _selectionWidthStyle); _paintSelection(context.canvas, effectiveOffset); } @@ -2175,8 +2219,10 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin { if (paintCursorAboveText) _textPainter.paint(context.canvas, effectiveOffset); - if (showCaret) - _paintCaret(context.canvas, effectiveOffset, _selection.extent); + if (showCaret) { + assert(selection != null); + _paintCaret(context.canvas, effectiveOffset, selection.extent); + } if (!paintCursorAboveText) _textPainter.paint(context.canvas, effectiveOffset); @@ -2243,10 +2289,11 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin { @override List debugDescribeChildren() { return [ - text.toDiagnosticsNode( - name: 'text', - style: DiagnosticsTreeStyle.transition, - ), + if (text != null) + 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 cc02bf6136..1162f58823 100644 --- a/packages/flutter/lib/src/rendering/error.dart +++ b/packages/flutter/lib/src/rendering/error.dart @@ -47,6 +47,8 @@ class RenderErrorBox extends RenderBox { builder.pushStyle(textStyle); builder.addText(message); _paragraph = builder.build(); + } else { + _paragraph = null; } } catch (error) { // Intentionally left empty. @@ -56,7 +58,8 @@ class RenderErrorBox extends RenderBox { /// The message to attempt to display at paint time. final String message; - ui.Paragraph _paragraph; + // TODO(ianh): should be final + /*late*/ ui.Paragraph/*?*/ _paragraph; @override double computeMaxIntrinsicWidth(double height) { diff --git a/packages/flutter/lib/src/rendering/flex.dart b/packages/flutter/lib/src/rendering/flex.dart index 76cb38b191..9b6330d36c 100644 --- a/packages/flutter/lib/src/rendering/flex.dart +++ b/packages/flutter/lib/src/rendering/flex.dart @@ -198,7 +198,7 @@ enum CrossAxisAlignment { 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) { @@ -508,9 +508,9 @@ class RenderFlex extends RenderBox with ContainerRenderObjectMixin 0) { final double maxChildExtent = canFlex ? (child == lastFlexChild ? (freeSpace - allocatedFlexSpace) : spacePerFlex * flex) : double.infinity; - double minChildExtent; + // TODO(ianh): this should be late final + /*late*/ double/*!*/ minChildExtent; switch (_getFit(child)) { case FlexFit.tight: assert(maxChildExtent < double.infinity); @@ -865,7 +867,6 @@ class RenderFlex extends RenderBox with ContainerRenderObjectMixin _constraints; + Constraints/*!*/ get constraints { + if (_constraints == null) + throw StateError('A RenderObject does not have any constraints before it has been laid out.'); + return _constraints/*!*/; + } Constraints _constraints; /// Verify that the object's constraints are being met. Override @@ -2492,7 +2499,7 @@ abstract class RenderObject extends AbstractNode with DiagnosticableTreeMixin im /// ``` /// {@end-tool} @protected - void describeSemanticsConfiguration(SemanticsConfiguration config) { + void describeSemanticsConfiguration(SemanticsConfiguration/*!*/ config) { // Nothing to do by default. } @@ -2890,7 +2897,7 @@ abstract class RenderObject extends AbstractNode with DiagnosticableTreeMixin im properties.add(FlagProperty('needsCompositing', value: _needsCompositing, ifTrue: 'needs compositing')); properties.add(DiagnosticsProperty('creator', debugCreator, defaultValue: null, level: DiagnosticLevel.debug)); properties.add(DiagnosticsProperty('parentData', parentData, tooltip: _debugCanParentUseSize == true ? 'can use size' : null, missingIfNull: true)); - properties.add(DiagnosticsProperty('constraints', constraints, missingIfNull: true)); + properties.add(DiagnosticsProperty('constraints', _constraints, missingIfNull: true)); // don't access it via the "layer" getter since that's only valid when we don't need paint properties.add(DiagnosticsProperty('layer', _layer, defaultValue: null)); properties.add(DiagnosticsProperty('semantics node', _semantics, defaultValue: null)); diff --git a/packages/flutter/lib/src/rendering/stack.dart b/packages/flutter/lib/src/rendering/stack.dart index c158d92c33..b6e7d74f21 100644 --- a/packages/flutter/lib/src/rendering/stack.dart +++ b/packages/flutter/lib/src/rendering/stack.dart @@ -62,22 +62,22 @@ class RelativeRect { /// 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,7 +134,7 @@ class RelativeRect { /// 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; @@ -492,7 +492,8 @@ class RenderStack extends RenderBox child.layout(childConstraints, parentUsesSize: true); - double x; + // TODO(ianh): x should be late final + /*late*/ double/*!*/ x; if (childParentData.left != null) { x = childParentData.left; } else if (childParentData.right != null) { @@ -504,7 +505,8 @@ class RenderStack extends RenderBox if (x < 0.0 || x + child.size.width > size.width) hasVisualOverflow = true; - double y; + // TODO(ianh): y should be late final + /*late*/ double/*!*/ y; if (childParentData.top != null) { y = childParentData.top; } else if (childParentData.bottom != null) { diff --git a/packages/flutter/lib/src/widgets/editable_text.dart b/packages/flutter/lib/src/widgets/editable_text.dart index 432f643e1e..34fcbd32f8 100644 --- a/packages/flutter/lib/src/widgets/editable_text.dart +++ b/packages/flutter/lib/src/widgets/editable_text.dart @@ -1145,13 +1145,16 @@ class EditableText extends StatefulWidget { final EdgeInsets scrollPadding; /// {@template flutter.widgets.editableText.enableInteractiveSelection} - /// If true, then long-pressing this TextField will select text and show the - /// cut/copy/paste menu, and tapping will move the text caret. + /// Whether to enable user interface affordances for changing the + /// text selection. /// - /// True by default. + /// For example, setting this to true will enable features such as + /// long-pressing the TextField to select text and show the + /// cut/copy/paste menu, and tapping to move the text caret. /// - /// If false, most of the accessibility support for selecting text, copy - /// and paste, and moving the caret will be disabled. + /// When this is false, the text selection cannot be adjusted by + /// the user, text cannot be copied, and the user cannot paste into + /// the text field from the clipboard. /// {@endtemplate} final bool enableInteractiveSelection; @@ -1186,7 +1189,12 @@ class EditableText extends StatefulWidget { /// {@endtemplate} final ScrollPhysics scrollPhysics; - /// {@macro flutter.rendering.editable.selectionEnabled} + /// {@template flutter.widgets.editableText.selectionEnabled} + /// Same as [enableInteractiveSelection]. + /// + /// This getter exists primarily for consistency with + /// [RenderEditable.selectionEnabled]. + /// {@endtemplate} bool get selectionEnabled => enableInteractiveSelection; /// {@template flutter.widgets.editableText.autofillHints} diff --git a/packages/flutter/test/material/button_bar_test.dart b/packages/flutter/test/material/button_bar_test.dart index 693eb10714..4f2a8be2f8 100644 --- a/packages/flutter/test/material/button_bar_test.dart +++ b/packages/flutter/test/material/button_bar_test.dart @@ -630,7 +630,7 @@ void main() { ); }); - testWidgets('_RenderButtonBarRow.constraints works before layout', (WidgetTester tester) async { + testWidgets('_RenderButtonBarRow.constraints does not work before layout', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp(home: ButtonBar()), Duration.zero, @@ -641,6 +641,6 @@ void main() { final RenderBox renderButtonBar = tester.renderObject(buttonBar) as RenderBox; expect(renderButtonBar.debugNeedsLayout, isTrue); - expect(renderButtonBar.constraints, isNull); + expect(() => renderButtonBar.constraints, throwsStateError); }); }