Skip to content

OverflowBox always sets its own size as constraints.biggest, while users frequently needs it to "shrink wrap" #129094

Description

@fzyzcjy

Is there an existing issue for this?

Steps to reproduce

Run the test

Expected results

Actual results

Firstly, when enableOverflowBox=false, the results are expected:

  • When contentSuperLong=false, i.e. content is short, the test passes
  • When contentSuperLong=true, i.e. content is too long and overflows, the test correctly prints an error saying "A RenderFlex overflowed by 9400 pixels on the bottom". That is expected, because our content is really too long.

Secondly, when enableOverflowBox=true, i.e. use OverflowBox, the results are less than optimal:

  • When contentSuperLong=false, i.e. content is short, the test fails. This is the main point the PR is going to solve. Here, OverflowBox always sets its own size as constraints.biggest, while users wants it to "shrink wrap", i.e. when child is small, the OverflowBox should be as small as child.
  • When contentSuperLong=true, i.e. content is too long and overflows, the OverflowBox does its job correctly.

In other words, the enableOverflowBox=true contentSuperLong=false needs to be fixed.

Code Fix

Please copy-paste the following MyOverflowBox, and modify usage of OverflowBox to MyOverflowBox.

Then, as can be seen, the enableOverflowBox=true contentSuperLong=false case now passes test, because it correctly shrink wraps.

Details
class MyOverflowBox extends SingleChildRenderObjectWidget {
  /// Creates a widget that lets its child overflow itself.
  const MyOverflowBox({
    super.key,
    this.alignment = Alignment.center,
    this.minWidth,
    this.maxWidth,
    this.minHeight,
    this.maxHeight,
    super.child,
  });

  /// How to align the child.
  ///
  /// The x and y values of the alignment control the horizontal and vertical
  /// alignment, respectively. An x value of -1.0 means that the left edge of
  /// the child is aligned with the left edge of the parent whereas an x value
  /// of 1.0 means that the right edge of the child is aligned with the right
  /// edge of the parent. Other values interpolate (and extrapolate) linearly.
  /// For example, a value of 0.0 means that the center of the child is aligned
  /// with the center of the parent.
  ///
  /// Defaults to [Alignment.center].
  ///
  /// See also:
  ///
  ///  * [Alignment], a class with convenient constants typically used to
  ///    specify an [AlignmentGeometry].
  ///  * [AlignmentDirectional], like [Alignment] for specifying alignments
  ///    relative to text direction.
  final AlignmentGeometry alignment;

  /// The minimum width constraint to give the child. Set this to null (the
  /// default) to use the constraint from the parent instead.
  final double? minWidth;

  /// The maximum width constraint to give the child. Set this to null (the
  /// default) to use the constraint from the parent instead.
  final double? maxWidth;

  /// The minimum height constraint to give the child. Set this to null (the
  /// default) to use the constraint from the parent instead.
  final double? minHeight;

  /// The maximum height constraint to give the child. Set this to null (the
  /// default) to use the constraint from the parent instead.
  final double? maxHeight;

  @override
  MyRenderConstrainedOverflowBox createRenderObject(BuildContext context) {
    return MyRenderConstrainedOverflowBox(
      alignment: alignment,
      minWidth: minWidth,
      maxWidth: maxWidth,
      minHeight: minHeight,
      maxHeight: maxHeight,
      textDirection: Directionality.maybeOf(context),
    );
  }

  @override
  void updateRenderObject(BuildContext context, MyRenderConstrainedOverflowBox renderObject) {
    renderObject
      ..alignment = alignment
      ..minWidth = minWidth
      ..maxWidth = maxWidth
      ..minHeight = minHeight
      ..maxHeight = maxHeight
      ..textDirection = Directionality.maybeOf(context);
  }

  @override
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
    properties.add(DiagnosticsProperty<AlignmentGeometry>('alignment', alignment));
    properties.add(DoubleProperty('minWidth', minWidth, defaultValue: null));
    properties.add(DoubleProperty('maxWidth', maxWidth, defaultValue: null));
    properties.add(DoubleProperty('minHeight', minHeight, defaultValue: null));
    properties.add(DoubleProperty('maxHeight', maxHeight, defaultValue: null));
  }
}

class MyRenderConstrainedOverflowBox extends RenderAligningShiftedBox {
  /// Creates a render object that lets its child overflow itself.
  MyRenderConstrainedOverflowBox({
    super.child,
    double? minWidth,
    double? maxWidth,
    double? minHeight,
    double? maxHeight,
    super.alignment,
    super.textDirection,
  })  : _minWidth = minWidth,
        _maxWidth = maxWidth,
        _minHeight = minHeight,
        _maxHeight = maxHeight;

  /// 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) {
    if (_minWidth == value) {
      return;
    }
    _minWidth = value;
    markNeedsLayout();
  }

  /// 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) {
    if (_maxWidth == value) {
      return;
    }
    _maxWidth = value;
    markNeedsLayout();
  }

  /// 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) {
    if (_minHeight == value) {
      return;
    }
    _minHeight = value;
    markNeedsLayout();
  }

  /// 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) {
    if (_maxHeight == value) {
      return;
    }
    _maxHeight = value;
    markNeedsLayout();
  }

  BoxConstraints _getInnerConstraints(BoxConstraints constraints) {
    return BoxConstraints(
      minWidth: _minWidth ?? constraints.minWidth,
      maxWidth: _maxWidth ?? constraints.maxWidth,
      minHeight: _minHeight ?? constraints.minHeight,
      maxHeight: _maxHeight ?? constraints.maxHeight,
    );
  }

  @override
  // bool get sizedByParent => true;
  bool get sizedByParent => false; // NOTE MODIFIED

  // NOTE MODIFIED
  // @override
  // Size computeDryLayout(BoxConstraints constraints) {
  //   return constraints.biggest;
  // }

  @override
  void performLayout() {
    if (child != null) {
      child?.layout(_getInnerConstraints(constraints), parentUsesSize: true);
      // alignChild(); // NOTE MODIFIED
    }

    size = child != null ? constraints.constrain(child!.size) : constraints.smallest; // NOTE MODIFIED

    if (child != null) {
      alignChild();
    }

    print('hi performLayout constraints=$constraints size=$size child.size=${child?.size}');
  }

  @override
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
    properties.add(DoubleProperty('minWidth', minWidth, ifNull: 'use parent minWidth constraint'));
    properties.add(DoubleProperty('maxWidth', maxWidth, ifNull: 'use parent maxWidth constraint'));
    properties.add(DoubleProperty('minHeight', minHeight, ifNull: 'use parent minHeight constraint'));
    properties.add(DoubleProperty('maxHeight', maxHeight, ifNull: 'use parent maxHeight constraint'));
  }
}

Code sample

Code sample
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';

void main() {
  for (final contentSuperLong in [false, true]) {
    for (final enableOverflowBox in [false, true]) {
      testWidgets('contentSuperLong=$contentSuperLong enableOverflowBox=$enableOverflowBox',
          (WidgetTester tester) async {
        final key = GlobalKey();

        final child = Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            SizedBox(width: 100, height: contentSuperLong ? 10000 : 100),
          ],
        );

        await tester.pumpWidget(
          MaterialApp(
            home: Stack(
              children: [
                Container(
                  key: key,
                  child: enableOverflowBox
                      ? OverflowBox(
                          maxHeight: 1000000,
                          child: child,
                        )
                      : child,
                ),
              ],
            ),
          ),
        );

        expect(tester.getBottomLeft(find.byKey(key)).dy, contentSuperLong ? 600 : 100);
      });
    }
  }
}

Screenshots or Video

Screenshots / Video demonstration

[Upload media here]

Logs

Logs
[Paste your logs here]

Flutter Doctor output

Doctor output
[Paste your output here]

Activity

  1. added
    in triagePresently being triaged by the triage team
    on Jun 19, 2023
  2. huycozy commented on Jun 19, 2023

    @huycozy
    Member

    Thanks for the report, @fzyzcjy. Reproduced this issue on the latest Flutter channels.

    Test output logs - default OverflowBox
    ══╡ EXCEPTION CAUGHT BY FLUTTER TEST FRAMEWORK ╞════════════════════════════════════════════════════
    The following TestFailure was thrown running a test:
    Expected: <100>
      Actual: <600.0>
    
    When the exception was thrown, this was the stack:
    #4      main.<anonymous closure> (file:///Users/huynq/Documents/NEVERCODE.IO/RepoduceProjects/reproduce_issues_2/test/overflowbox_129094.dart:37:9)
    <asynchronous suspension>
    <asynchronous suspension>
    (elided one frame from package:stack_trace)
    
    This was caught by the test expectation on the following line:
      file:///Users/huynq/Documents/NEVERCODE.IO/RepoduceProjects/reproduce_issues_2/test/overflowbox_129094.dart line 37
    The test description was:
      contentSuperLong=false enableOverflowBox=true
    ════════════════════════════════════════════════════════════════════════════════════════════════════
    
    Test failed. See exception logs above.
    The test description was: contentSuperLong=false enableOverflowBox=true
    
    ══╡ EXCEPTION CAUGHT BY RENDERING LIBRARY ╞═════════════════════════════════════════════════════════
    The following assertion was thrown during layout:
    A RenderFlex overflowed by 9400 pixels on the bottom.
    
    The relevant error-causing widget was:
      Column
      Column:file:///Users/huynq/Documents/NEVERCODE.IO/RepoduceProjects/reproduce_issues_2/test/overflowbox_129094.dart:12:23
    
    The overflowing RenderFlex has an orientation of Axis.vertical.
    The edge of the RenderFlex that is overflowing has been marked in the rendering with a yellow and
    black striped pattern. This is usually caused by the contents being too big for the RenderFlex.
    Consider applying a flex factor (e.g. using an Expanded widget) to force the children of the
    RenderFlex to fit within the available space instead of being sized to their natural size.
    This is considered an error condition because it indicates that there is content that cannot be
    seen. If the content is legitimately bigger than the available space, consider clipping it with a
    ClipRect widget before putting it in the flex, or using a scrollable container rather than a Flex,
    like a ListView.
    The specific RenderFlex in question is: RenderFlex#b7fe2 relayoutBoundary=up1 OVERFLOWING:
      creator: Column ← Container-[GlobalKey#63822] ← Stack ← Semantics ← Builder ←
        RepaintBoundary-[GlobalKey#60772] ← IgnorePointer ← AnimatedBuilder ← SnapshotWidget ←
        _ZoomExitTransition ← SnapshotWidget ← _ZoomEnterTransition ← ⋯
      parentData: not positioned; offset=Offset(0.0, 0.0) (can use size)
      constraints: BoxConstraints(0.0<=w<=800.0, 0.0<=h<=600.0)
      size: Size(100.0, 600.0)
      direction: vertical
      mainAxisAlignment: start
      mainAxisSize: min
      crossAxisAlignment: center
      verticalDirection: down
    ◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤
    ════════════════════════════════════════════════════════════════════════════════════════════════════
    
    Test failed. See exception logs above.
    The test description was: contentSuperLong=true enableOverflowBox=false
    
    Test output logs - MyOverflowBox
    hi performLayout constraints=BoxConstraints(0.0<=w<=800.0, 0.0<=h<=600.0) size=Size(100.0, 100.0) child.size=Size(100.0, 100.0)
    ══╡ EXCEPTION CAUGHT BY RENDERING LIBRARY ╞═════════════════════════════════════════════════════════
    The following assertion was thrown during layout:
    A RenderFlex overflowed by 9400 pixels on the bottom.
    
    The relevant error-causing widget was:
      Column
      Column:file:///Users/huynq/Documents/NEVERCODE.IO/RepoduceProjects/reproduce_issues_2/test/overflowbox_129094.dart:12:23
    
    The overflowing RenderFlex has an orientation of Axis.vertical.
    The edge of the RenderFlex that is overflowing has been marked in the rendering with a yellow and
    black striped pattern. This is usually caused by the contents being too big for the RenderFlex.
    Consider applying a flex factor (e.g. using an Expanded widget) to force the children of the
    RenderFlex to fit within the available space instead of being sized to their natural size.
    This is considered an error condition because it indicates that there is content that cannot be
    seen. If the content is legitimately bigger than the available space, consider clipping it with a
    ClipRect widget before putting it in the flex, or using a scrollable container rather than a Flex,
    like a ListView.
    The specific RenderFlex in question is: RenderFlex#33060 relayoutBoundary=up1 OVERFLOWING:
      creator: Column ← Container-[GlobalKey#9cf7f] ← Stack ← Semantics ← Builder ←
        RepaintBoundary-[GlobalKey#42076] ← IgnorePointer ← AnimatedBuilder ← SnapshotWidget ←
        _ZoomExitTransition ← SnapshotWidget ← _ZoomEnterTransition ← ⋯
      parentData: not positioned; offset=Offset(0.0, 0.0) (can use size)
      constraints: BoxConstraints(0.0<=w<=800.0, 0.0<=h<=600.0)
      size: Size(100.0, 600.0)
      direction: vertical
      mainAxisAlignment: start
      mainAxisSize: min
      crossAxisAlignment: center
      verticalDirection: down
    ◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤
    ════════════════════════════════════════════════════════════════════════════════════════════════════
    
    Test failed. See exception logs above.
    The test description was: contentSuperLong=true enableOverflowBox=false
    
    hi performLayout constraints=BoxConstraints(0.0<=w<=800.0, 0.0<=h<=600.0) size=Size(100.0, 600.0) child.size=Size(100.0, 10000.0)
    
    flutter doctor -v (stable and master)
    [✓] Flutter (Channel stable, 3.10.5, on macOS 13.0.1 22A400 darwin-x64, locale en-VN)
        • Flutter version 3.10.5 on channel stable at /Users/huynq/Documents/GitHub/flutter
        • Upstream repository https://github.com/flutter/flutter.git
        • Framework revision 796c8ef792 (29 hours ago), 2023-06-13 15:51:02 -0700
        • Engine revision 45f6e00911
        • Dart version 3.0.5
        • DevTools version 2.23.1
    
    [✓] Android toolchain - develop for Android devices (Android SDK version 32.0.0)
        • Android SDK at /Users/huynq/Library/Android/sdk
        • Platform android-33, build-tools 32.0.0
        • ANDROID_HOME = /Users/huynq/Library/Android/sdk
        • Java binary at: /Applications/Android Studio.app/Contents/jbr/Contents/Home/bin/java
        • Java version OpenJDK Runtime Environment (build 17.0.6+0-17.0.6b802.4-9586694)
        • All Android licenses accepted.
    
    [✓] Xcode - develop for iOS and macOS (Xcode 14.3)
        • Xcode at /Applications/Xcode.app/Contents/Developer
        • Build 14E222b
        • CocoaPods version 1.11.3
    
    [✓] Chrome - develop for the web
        • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome
    
    [✓] Android Studio (version 2022.2)
        • Android Studio at /Applications/Android Studio.app/Contents
        • Flutter plugin can be installed from:
          🔨 https://plugins.jetbrains.com/plugin/9212-flutter
        • Dart plugin can be installed from:
          🔨 https://plugins.jetbrains.com/plugin/6351-dart
        • Java version OpenJDK Runtime Environment (build 17.0.6+0-17.0.6b802.4-9586694)
    
    [✓] VS Code (version 1.79.0)
        • VS Code at /Applications/Visual Studio Code.app/Contents
        • Flutter extension version 3.66.0
    
    [✓] Connected device (5 available)
        • Pixel 3a (mobile)      • 964AY0WL20                               • android-arm64  • Android 12 (API 32)
        • iPhone (mobile)        • d9a94afe2b649fef56ba0bfeb052f0f2a7dae95e • ios            • iOS 15.7.2 19H218
        • iPhone 14 Pro (mobile) • 98082851-A0C4-4E39-A310-21C48B10A364     • ios            • com.apple.CoreSimulator.SimRuntime.iOS-16-4 (simulator)
        • macOS (desktop)        • macos                                    • darwin-x64     • macOS 13.0.1 22A400 darwin-x64
        • Chrome (web)           • chrome                                   • web-javascript • Google Chrome 114.0.5735.133
    
    [✓] Network resources
        • All expected network resources are available.
    
    • No issues found!
    [!] Flutter (Channel master, 3.12.0-4.0.pre.111, on macOS 13.0.1 22A400 darwin-x64, locale en-VN)
        • Flutter version 3.12.0-4.0.pre.111 on channel master at /Users/huynq/Documents/GitHub/flutter_master
        ! Warning: `flutter` on your path resolves to /Users/huynq/Documents/GitHub/flutter/bin/flutter, which is not inside your current
          Flutter SDK checkout at /Users/huynq/Documents/GitHub/flutter_master. Consider adding
          /Users/huynq/Documents/GitHub/flutter_master/bin to the front of your path.
        ! Warning: `dart` on your path resolves to /Users/huynq/Documents/GitHub/flutter/bin/dart, which is not inside your current Flutter SDK
          checkout at /Users/huynq/Documents/GitHub/flutter_master. Consider adding /Users/huynq/Documents/GitHub/flutter_master/bin to the
          front of your path.
        • Upstream repository https://github.com/flutter/flutter.git
        • Framework revision 0dadf4089b (61 minutes ago), 2023-06-18 22:06:20 -0400
        • Engine revision d298f0bf72
        • Dart version 3.1.0 (build 3.1.0-226.0.dev)
        • DevTools version 2.24.0
        • If those were intentional, you can disregard the above warnings; however it is recommended to use "git" directly to perform update
          checks and upgrades.
    
    [✓] Android toolchain - develop for Android devices (Android SDK version 32.0.0)
        • Android SDK at /Users/huynq/Library/Android/sdk
        • Platform android-33, build-tools 32.0.0
        • ANDROID_HOME = /Users/huynq/Library/Android/sdk
        • Java binary at: /Applications/Android Studio.app/Contents/jbr/Contents/Home/bin/java
        • Java version OpenJDK Runtime Environment (build 17.0.6+0-17.0.6b802.4-9586694)
        • All Android licenses accepted.
    
    [✓] Xcode - develop for iOS and macOS (Xcode 14.3)
        • Xcode at /Applications/Xcode.app/Contents/Developer
        • Build 14E222b
        • CocoaPods version 1.11.3
    
    [✓] Chrome - develop for the web
        • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome
    
    [✓] Android Studio (version 2022.2)
        • Android Studio at /Applications/Android Studio.app/Contents
        • Flutter plugin can be installed from:
          🔨 https://plugins.jetbrains.com/plugin/9212-flutter
        • Dart plugin can be installed from:
          🔨 https://plugins.jetbrains.com/plugin/6351-dart
        • Java version OpenJDK Runtime Environment (build 17.0.6+0-17.0.6b802.4-9586694)
    
    [✓] VS Code (version 1.79.2)
        • VS Code at /Applications/Visual Studio Code.app/Contents
        • Flutter extension version 3.66.0
    
    [✓] Connected device (3 available)
        • Pixel 3a (mobile) • 964AY0WL20 • android-arm64  • Android 12 (API 32)
        • macOS (desktop)   • macos      • darwin-x64     • macOS 13.0.1 22A400 darwin-x64
        • Chrome (web)      • chrome     • web-javascript • Google Chrome 114.0.5735.133
    
    [✓] Network resources
        • All expected network resources are available.
    
    ! Doctor found issues in 1 category.
  3. added
    frameworkflutter/packages/flutter repository. See also f: labels.
    has reproducible stepsThe issue has been confirmed reproducible and is ready to work on
    and removed
    in triagePresently being triaged by the triage team
    on Jun 19, 2023
  4. added
    P3Issues that are less important to the Flutter project
    on Jun 20, 2023
  5. added
    r: fixedIssue is closed as already fixed in a newer version
    on Oct 25, 2023
  6. github-actions commented on Nov 8, 2023

    @github-actions

    This thread has been automatically locked since there has not been any recent activity after it was closed. If you are still experiencing a similar issue, please open a new bug, including the output of flutter doctor -v and a minimal reproduction of the issue.

  7. locked as resolved and limited conversation to collaborators on Nov 8, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    P3Issues that are less important to the Flutter projectfound in release: 3.10Found to occur in 3.10found in release: 3.12Found to occur in 3.12frameworkflutter/packages/flutter repository. See also f: labels.has reproducible stepsThe issue has been confirmed reproducible and is ready to work onr: fixedIssue is closed as already fixed in a newer versionteam-frameworkOwned by Framework teamtriaged-frameworkTriaged by Framework team

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions