在SingleChildScrollView中使用OverflowBox覆盖padding
在SingleChildScrollView中使用OverflowBox覆盖padding
我想尝试在SingleChildScrollView中使用OverflowBox来覆盖padding,但我无法成功。\n我的示例代码如下:\nScreen(\n child: Scaffold(\n backgroundColor: Palette.white,\n appBar: ExtendedAppBar(\n title: HeaderTitle(title: L.of(context).catalogFilterTitle, color: Palette.white),\n onCloseCallback: () => Navigator.of(context).pop(false),\n ),\n body: SingleChildScrollView(\n padding: const EdgeInsets.only(left: 17.0, right: 17.0),\n child: Column(\n crossAxisAlignment: CrossAxisAlignment.start,\n children: [\n ...,\n Expanded(\n child: OverflowBox(\n maxWidth: MediaQuery.of(context).size.width,\n child: Container(\n color: Colors.red.shade300,\n child: Center(\n child: Text(\'No padding on this one!\'),\n ),\n ),\n ),\n ),\n ...,\n ],\n ),\n ),\n floatingActionButton: RaisedButton(\n ...\n ),\n floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,\n ),\n);\n
\n当我运行时,出现以下异常:\n════════ Exception caught by rendering library ═════════════════════════════════════════════════════\nRenderBox was not laid out: _RenderScrollSemantics#98805 relayoutBoundary=up7 NEEDS-PAINT\n\'package:flutter/src/rendering/box.dart\':\nFailed assertion: line 1694 pos 12: \'hasSize\'\nThe relevant error-causing widget was: \n...\n════════════════════════════════════════════════════════════════════════════════════════════════════\n════════ Exception caught by rendering library ═════════════════════════════════════════════════════\nRenderBox was not laid out: _RenderSingleChildViewport#feeb7 relayoutBoundary=up13 NEEDS-PAINT\n\'package:flutter/src/rendering/box.dart\':\nFailed assertion: line 1694 pos 12: \'hasSize\'\nThe relevant error-causing widget was: \n...\n════════════════════════════════════════════════════════════════════════════════════════════════════\n
\n有人能解释一下为什么会出现这个问题吗?:)\n提前感谢。
问题的原因:在SingleChildScrollView中使用padding属性设置了左右边距,但是由于SingleChildScrollView默认会尽可能展示所有内容,如果内容超过屏幕大小,会出现滚动效果。当内容超过屏幕大小时,padding属性会失效,因为SingleChildScrollView会尽可能展示所有内容,而不会考虑padding属性。
解决方法:使用OverflowBox组件来覆盖padding属性。OverflowBox可以根据需要来裁剪或放大子组件,以适应给定的限制。通过将OverflowBox作为SingleChildScrollView的子组件,并设置maxWidth属性为屏幕宽度,可以实现类似于padding的效果,同时保留SingleChildScrollView的滚动功能。
具体代码如下:
SingleChildScrollView(
child: IntrinsicHeight(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(
child: OverflowBox(
maxWidth: MediaQuery.of(context).size.width,
child: Container(
color: Colors.red.shade300,
child: Center(
child: Text('No padding on this one!'),
),
),
),
),
],
),
),
)
通过将SingleChildScrollView的padding属性移除,并将OverflowBox作为SingleChildScrollView的子组件,并设置maxWidth属性为屏幕宽度,可以实现在SingleChildScrollView中添加padding的效果,并保留滚动功能。