【问题标题】:Add button(s) or any content below a ListView causing hasSize rendering issues在 ListView 下添加按钮或任何内容导致 hasSize 呈现问题
【发布时间】:2021-06-01 13:09:21
【问题描述】:

我需要在 2 个按钮上方放置一个 ListView(在一个 Column 中)但是我很难做到,见下文。

我想要实现的示例是 条款和条件 页面,其中包含包含文本的列表视图,屏幕底部固定有 2 个按钮,允许用户滚动并随时单击Accept/Decline.

问题:

#1 & #3 是带有渐变背景集的脚手架模板的一部分。我用一个 Widget 填充内容,它应该在这个特定的 UI 中包含 ListViewButtons。

#2 是导致问题的原因。当尝试渲染以下 UI 时,下面的堆栈跟踪显示

import 'package:testapp/activities/ui_privacy.dart';
import 'package:testapp/ui/components/ui_button.dart';
import 'package:testapp/ui/components/ui_button_exit.dart';
import 'package:testapp/ui/design/ui_component_base_content_centre.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';

class UiTermsConditions extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final Widget terms = ListView(
      children: [
        Container(
          width: double.infinity,
          padding: const EdgeInsets.only(top: 8, bottom: 8),
          child: Text("Terms and Conditions",
              style: TextStyle(fontWeight: FontWeight.bold),
              textAlign: TextAlign.left),
        ),
        Container(
          width: double.infinity,
          child: Text(
            'These Terms and Conditions constitute a legally binding agreement made between you, whether personally or on behalf of an entity (“you”) and [business entity name] (“we,” “us” or “our”), concerning your access to and use of the [website name.com] website as well as any other media form, media channel, mobile website or mobile application related, linked, or otherwise connected thereto (collectively, the “Site”).'
            '\n\n'
            'You agree that by accessing the Site, you have read, understood, and agree to be bound by all of these Terms and Conditions. If you do not agree with all of these Terms and Conditions, then you are expressly prohibited from using the Site and you must discontinue use immediately.'
            '\n\n'
            'Supplemental terms and conditions or documents that may be posted on the Site from time to time are hereby expressly incorporated herein by reference. We reserve the right, in our sole discretion, to make changes or modifications to these Terms and Conditions at any time and for any reason.'
            '\n\n'
            'We will alert you about any changes by updating the “Last updated” date of these Terms and Conditions, and you waive any right to receive specific notice of each such change.'
            '\n\n'
            'It is your responsibility to periodically review these Terms and Conditions to stay informed of updates. You will be subject to, and will be deemed to have been made aware of and to have accepted, the changes in any revised Terms and Conditions by your continued use of the Site after the date such revised Terms and Conditions are posted.'
            '\n\n'
            'The information provided on the Site is not intended for distribution to or use by any person or entity in any jurisdiction or country where such distribution or use would be contrary to law or regulation or which would subject us to any registration requirement within such jurisdiction or country.'
            '\n\n'
            'Accordingly, those persons who choose to access the Site from other locations do so on their own initiative and are solely responsible for compliance with local laws, if and to the extent local laws are applicable.',
            softWrap: true,
          ),
        )
      ],
    );

    final Widget buttonRow = Container(
      padding: const EdgeInsets.only(top: 16),
      child: Column(
        children: [
          UiButton(
            text: "Accept",
            callback: () {
              Navigator.of(context)
                  .push(MaterialPageRoute(builder: (context) => UiPrivacy()));
            },
          ),
          UiButtonExit(
            text: "Decline",
            flat: true,
            padding: const EdgeInsets.only(top: 16),
          ),
        ],
      ),
    );


    ==================================== IMPORTANT BITS BELOW ======================

    final content = Column(
      children: [
        Expanded(
            // terms is a ListView
            child: terms
        ),
        buttonRow
      ],
    );
    return UiBaseContentCenter(widget: content);
  }
}

已发布解决方案:

有许多已经发布的解决方案,但是在尝试每个之后 - 我都没有成功。

  • 这个post 暗示了无法将ListView 放在Expanded 中的原因,但在呈现时会引发以下呈现错误。

     ======== Exception caught by rendering library ===================================================== The following assertion was thrown during performLayout(): RenderFlex children have non-zero flex but incoming height constraints are unbounded.
    
      When a column is in a parent that does not provide a finite height constraint, for example if it is in a vertical scrollable, it will try to shrink-wrap its children along the vertical 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 vertical direction. These two directives are mutually exclusive. If a parent is to shrink-wrap its child, the child cannot simultaneously expand to fit its parent.
    
      Consider setting mainAxisSize to MainAxisSize.min and using FlexFit.loose fits for the flexible children (using Flexible rather than Expanded). This will allow the flexible children to size themselves to less than the infinite remaining space they would otherwise be forced to take, and then will cause the RenderFlex to shrink-wrap the children rather than expanding to fit the maximum constraints provided by the parent. (removed for brevity)
    

TLD;DR Column 尝试缩小和最小化使用的空间,而 Expanded 尝试填充剩余空间,这两个操作是矛盾的。

设置 MainAxisSize.min 并将 Expanded 更改为 Flexible 会出现以下渲染错误:

  Performing hot reload...
  Syncing files to device sdk gphone x86...

   ======== Exception caught by rendering library =====================================================
    The following assertion was thrown during performResize():
    Vertical viewport was given unbounded height.
    
    Viewports expand in the scrolling direction to fill their container. In this case, a vertical viewport was given an unlimited amount of vertical space in which to expand. This situation typically happens when a scrollable widget is nested inside another scrollable widget.
    
    If this widget is always nested in a scrollable widget there is no need to use a viewport because there will always be enough vertical space for the children. In this case, consider using a Column instead. Otherwise, consider using the "shrinkWrap" property (or a ShrinkWrappingViewport) to size the height of the viewport to the sum of the heights of its children.
    
    The relevant error-causing widget was: 
      ListView file:///C:/Users/CybeX/testapp/testapp-mobile-flutter/lib/activities/ui_terms_conditions.dart:11:26
    When the exception was thrown, this was the stack: 
    #0      RenderViewport.performResize.<anonymous closure> (package:flutter/src/rendering/viewport.dart:1356:15)
    #1      RenderViewport.performResize (package:flutter/src/rendering/viewport.dart:1417:6)
    #2      RenderObject.layout (package:flutter/src/rendering/object.dart:1756:9)
    #3      RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:113:14)
    #4      RenderObject.layout (package:flutter/src/rendering/object.dart:1777:7)
    ...
    The following RenderObject was being processed when the exception was fired: RenderViewport#a87b9 NEEDS-LAYOUT NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
    ...  needs compositing
    ...  parentData: <none> (can use size)
    ...  constraints: BoxConstraints(0.0<=w<=376.7, 0.0<=h<=Infinity)
    ...  size: MISSING
    ...  axisDirection: down
    ...  crossAxisDirection: right
    ...  offset: ScrollPositionWithSingleContext#ad184(offset: 0.0, range: null..null, viewport: null, ScrollableState, AlwaysScrollableScrollPhysics -> ClampingScrollPhysics -> RangeMaintainingScrollPhysics, IdleScrollActivity#a328b, ScrollDirection.idle)
    ...  anchor: 0.0
    RenderObject: RenderViewport#a87b9 NEEDS-LAYOUT NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
      needs compositing
      parentData: <none> (can use size)
      constraints: BoxConstraints(0.0<=w<=376.7, 0.0<=h<=Infinity)
      size: MISSING
      axisDirection: down
      crossAxisDirection: right
      offset: ScrollPositionWithSingleContext#ad184(offset: 0.0, range: null..null, viewport: null, ScrollableState, AlwaysScrollableScrollPhysics -> ClampingScrollPhysics -> RangeMaintainingScrollPhysics, IdleScrollActivity#a328b, ScrollDirection.idle)
      anchor: 0.0
    ...  center child: RenderSliverPadding#256bb NEEDS-LAYOUT NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
    ...    parentData: paintOffset=Offset(0.0, 0.0)
    ...    constraints: MISSING
    ...    geometry: null
    ...    padding: EdgeInsets(0.0, 24.0, 0.0, 0.0)
    ...    textDirection: ltr
    ...    child: RenderSliverList#c59be NEEDS-LAYOUT NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
    ...      parentData: paintOffset=Offset(0.0, 0.0)
    ...      constraints: MISSING
    ...      geometry: null
    ...      no children current live
    ====================================================================================================
    
    ======== Exception caught by rendering library =====================================================
    RenderBox was not laid out: RenderViewport#a87b9 NEEDS-LAYOUT NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
    'package:flutter/src/rendering/box.dart':
    Failed assertion: line 1785 pos 12: 'hasSize'
    The relevant error-causing widget was: 
      ListView file:///C:/Users/CybeX/testapp/testapp-mobile-flutter/lib/activities/ui_terms_conditions.dart:11:26
    ====================================================================================================
    
    ======== Exception caught by rendering library =====================================================
    RenderBox was not laid out: RenderViewport#a87b9 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
    'package:flutter/src/rendering/box.dart':
    Failed assertion: line 1785 pos 12: 'hasSize'
    The relevant error-causing widget was: 
      ListView file:///C:/Users/CybeX/testapp/testapp-mobile-flutter/lib/activities/ui_terms_conditions.dart:11:26
    ====================================================================================================
    
    ======== Exception caught by rendering library =====================================================
    RenderBox was not laid out: RenderIgnorePointer#14129 relayoutBoundary=up14 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
    'package:flutter/src/rendering/box.dart':
    Failed assertion: line 1785 pos 12: 'hasSize'
    The relevant error-causing widget was: 
      ListView file:///C:/Users/CybeX/testapp/testapp-mobile-flutter/lib/activities/ui_terms_conditions.dart:11:26
    ====================================================================================================
    
    ======== Exception caught by rendering library =====================================================
    RenderBox was not laid out: RenderSemanticsAnnotations#1b4f6 relayoutBoundary=up13 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
    'package:flutter/src/rendering/box.dart':
    Failed assertion: line 1785 pos 12: 'hasSize'
    The relevant error-causing widget was: 
      ListView file:///C:/Users/CybeX/testapp/testapp-mobile-flutter/lib/activities/ui_terms_conditions.dart:11:26
    ====================================================================================================
    Reloaded 0 of 916 libraries in 223ms.
    
    ======== Exception caught by rendering library =====================================================
    RenderBox was not laid out: RenderPointerListener#48079 relayoutBoundary=up12 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
    'package:flutter/src/rendering/box.dart':
    Failed assertion: line 1785 pos 12: 'hasSize'
    The relevant error-causing widget was: 
      ListView file:///C:/Users/CybeX/testapp/testapp-mobile-flutter/lib/activities/ui_terms_conditions.dart:11:26
    ====================================================================================================
    
    ======== Exception caught by rendering library =====================================================
    The following assertion was thrown during performLayout():
    RenderBox was not laid out: RenderSemanticsGestureHandler#beaa9 relayoutBoundary=up11 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
    'package:flutter/src/rendering/box.dart':
    Failed assertion: line 1785 pos 12: 'hasSize'
    
    
    Either the assertion indicates an error in the framework itself, or we should provide substantially more information in this error message to help you determine and fix the underlying cause.
    In either case, please report this assertion by filing a bug on GitHub:
      https://github.com/flutter/flutter/issues/new?template=BUG.md
    
    The relevant error-causing widget was: 
      ListView file:///C:/Users/CybeX/testapp/testapp-mobile-flutter/lib/activities/ui_terms_conditions.dart:11:26
    When the exception was thrown, this was the stack: 
    #2      RenderBox.size (package:flutter/src/rendering/box.dart:1785:12)
    #3      RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:114:21)
    #4      RenderObject.layout (package:flutter/src/rendering/object.dart:1777:7)
    #5      RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:113:14)
    #6      RenderObject.layout (package:flutter/src/rendering/object.dart:1777:7)
    ...
    The following RenderObject was being processed when the exception was fired: RenderPointerListener#60907 relayoutBoundary=up10 NEEDS-LAYOUT NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
    ...  needs compositing
    ...  parentData: <none> (can use size)
    ...  constraints: BoxConstraints(0.0<=w<=376.7, 0.0<=h<=Infinity)
    ...  size: MISSING
    ...  behavior: deferToChild
    ...  listeners: signal
    RenderObject: RenderPointerListener#60907 relayoutBoundary=up10 NEEDS-LAYOUT NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
      needs compositing
      parentData: <none> (can use size)
      constraints: BoxConstraints(0.0<=w<=376.7, 0.0<=h<=Infinity)
      size: MISSING
      behavior: deferToChild
      listeners: signal
    ...  child: RenderSemanticsGestureHandler#beaa9 relayoutBoundary=up11 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
    ...    needs compositing
    ...    parentData: <none> (can use size)
    ...    constraints: BoxConstraints(0.0<=w<=376.7, 0.0<=h<=Infinity)
    ...    size: MISSING
    ...    gestures: <none>
    ...    child: RenderPointerListener#48079 relayoutBoundary=up12 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
    ...      needs compositing
    ...      parentData: <none> (can use size)
    ...      constraints: BoxConstraints(0.0<=w<=376.7, 0.0<=h<=Infinity)
    ...      size: MISSING
    ...      behavior: opaque
    ...      listeners: down
    ...      child: RenderSemanticsAnnotations#1b4f6 relayoutBoundary=up13 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
    ...        needs compositing
    ...        parentData: <none> (can use size)
    ...        constraints: BoxConstraints(0.0<=w<=376.7, 0.0<=h<=Infinity)
    ...        size: MISSING
    ...        child: RenderIgnorePointer#14129 relayoutBoundary=up14 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
    ...          needs compositing
    ...          parentData: <none> (can use size)
    ...          constraints: BoxConstraints(0.0<=w<=376.7, 0.0<=h<=Infinity)
    ...          size: MISSING
    ...          ignoring: false
    ...          ignoringSemantics: false
    ====================================================================================================
    
    ======== Exception caught by rendering library =====================================================
    RenderBox was not laid out: RenderPointerListener#60907 relayoutBoundary=up10 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
    'package:flutter/src/rendering/box.dart':
    Failed assertion: line 1785 pos 12: 'hasSize'
    The relevant error-causing widget was: 
      ListView file:///C:/Users/CybeX/testapp/testapp-mobile-flutter/lib/activities/ui_terms_conditions.dart:11:26
    ====================================================================================================
    
    ======== Exception caught by rendering library =====================================================
    RenderBox was not laid out: _RenderScrollSemantics#24769 relayoutBoundary=up9 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
    'package:flutter/src/rendering/box.dart':
    Failed assertion: line 1785 pos 12: 'hasSize'
    The relevant error-causing widget was: 
      ListView file:///C:/Users/CybeX/testapp/testapp-mobile-flutter/lib/activities/ui_terms_conditions.dart:11:26
    ====================================================================================================
    
    ======== Exception caught by rendering library =====================================================
    RenderBox was not laid out: RenderRepaintBoundary#a21f7 relayoutBoundary=up8 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
    'package:flutter/src/rendering/box.dart':
    Failed assertion: line 1785 pos 12: 'hasSize'
    The relevant error-causing widget was: 
      ListView file:///C:/Users/CybeX/testapp/testapp-mobile-flutter/lib/activities/ui_terms_conditions.dart:11:26
    ====================================================================================================
    
    ======== Exception caught by rendering library =====================================================
    RenderBox was not laid out: RenderCustomPaint#5f4f4 relayoutBoundary=up7 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
    'package:flutter/src/rendering/box.dart':
    Failed assertion: line 1785 pos 12: 'hasSize'
    The relevant error-causing widget was: 
      ListView file:///C:/Users/CybeX/testapp/testapp-mobile-flutter/lib/activities/ui_terms_conditions.dart:11:26
    ====================================================================================================
    
    ======== Exception caught by rendering library =====================================================
    RenderBox was not laid out: RenderRepaintBoundary#f535d relayoutBoundary=up6 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
    'package:flutter/src/rendering/box.dart':
    Failed assertion: line 1785 pos 12: 'hasSize'
    The relevant error-causing widget was: 
      Column file:///C:/Users/CybeX/testapp/testapp-mobile-flutter/lib/activities/ui_terms_conditions.dart:62:21
    ====================================================================================================
    
    ======== Exception caught by rendering library =====================================================
    RenderBox was not laid out: RenderRepaintBoundary#f535d relayoutBoundary=up6 NEEDS-PAINT
    'package:flutter/src/rendering/box.dart':
    Failed assertion: line 1785 pos 12: 'hasSize'
    The relevant error-causing widget was: 
      Column file:///C:/Users/CybeX/testapp/testapp-mobile-flutter/lib/activities/ui_terms_conditions.dart:62:21
    ====================================================================================================
    
    ======== Exception caught by rendering library =====================================================
    A RenderFlex overflowed by 167 pixels on the bottom.
    The relevant error-causing widget was: 
      Column file:///C:/Users/CybeX/testapp/testapp-mobile-flutter/lib/ui/design/ui_component_base_content_centre.dart:16:14
    ====================================================================================================
  • 这篇文章建议使用Slivers,我复制并粘贴了示例,但这不是滚动的(它可能只是我的模拟器)

  • 我尝试了其他一些建议,但已经迷失了方向。

任何实现如此简单的 UI 设计的建议都将不胜感激!

更多代码:

UIBaseContentCenter.dart

import 'package:testapp/ui/design/ui_component_base.dart';
import 'package:testapp/ui/layout/ui_component_logo_top.dart';
import 'package:testapp/ui/layout/ui_component_trademark_bottom.dart';
import 'package:flutter/widgets.dart';

class UiBaseContentCenter extends StatelessWidget {
  final Widget widget;
  final Widget bottomNavBar;

  const UiBaseContentCenter({Key key, this.widget, this.bottomNavBar}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    var uiComponentTrademarkBottom = UiComponentTrademarkBottom();
    final Widget mainComponent = Container(
      child: Column(
        children: [
          UiComponentLogoTop(),
          widget,
          uiComponentTrademarkBottom
        ],
      ),
    );

    return UiBase(widget: mainComponent, bottomNavigationBar: bottomNavBar);
  }
}

根 UI 支架

UiBase.dart

import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_platform_widgets/flutter_platform_widgets.dart';

import '../app_theme.dart';

class UiBase extends StatelessWidget {
  final Widget widget;
  final AppBar appBar;
  final BottomNavigationBar bottomNavigationBar;

  const UiBase({Key key, this.widget, this.appBar, this.bottomNavigationBar})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    if (appBar != null && bottomNavigationBar != null) {
      return Scaffold(
        appBar: appBar,
        body: Container(
            padding: standardSideInsets,
            width: double.infinity,
            decoration: AppTheme().backgroundDecorationGradient,
            child: widget),
        bottomNavigationBar: bottomNavigationBar,
      );
    } else if (appBar != null && bottomNavigationBar == null) {
      return Scaffold(
        appBar: appBar,
        body: Container(
            padding: standardSideInsets,
            width: double.infinity,
            decoration: AppTheme().backgroundDecorationGradient,
            child: widget),
      );
    } else if (appBar == null && bottomNavigationBar != null) {
      return Scaffold(
        body: Container(
            padding: standardSideInsets,
            width: double.infinity,
            decoration: AppTheme().backgroundDecorationGradient,
            child: widget),
        bottomNavigationBar: bottomNavigationBar,
      );
    } else {
      return Scaffold(
        body: Container(
            padding: standardSideInsets,
            width: double.infinity,
            decoration: AppTheme().backgroundDecorationGradient,
            child: widget),
      );
    }
  }
}

【问题讨论】:

  • 我添加了一个答案,但我不知道它是否能解决您的问题,尝试像我在此 gist here 中所做的那样,在 layoutbuider 中添加列表视图,如果它发生在我添加答案。

标签: android flutter listview flutter-layout flutter-listview


【解决方案1】:

在你的 UIBaseContentCenter.dart

改变

   final Widget mainComponent = Container(
      child: Column(
        children: [
          UiComponentLogoTop(),
          widget, // Here is the issue
          uiComponentTrademarkBottom
        ],
      ),
    );

   final Widget mainComponent = Container(
      child: Column(
        children: [
          UiComponentLogoTop(),
          Expanded(child: widget),
          uiComponentTrademarkBottom
        ],
      ),
    );

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-03
    • 1970-01-01
    • 1970-01-01
    • 2014-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多