Flutter/Dart - A RenderFlex overflowed by 99804 pixels on the bottom - flutter

Can anybody see why I'm getting this error on the first child: Column? I'm using a stack in my build. and tried wrapping each widget in a Flexible widget but can't figure out where the code is overflowing. The screen flashes the telltale yellow/black renderflex lines for just a second but then seems to render just fine. The messages in the console are annoying though as is the little yellow/black flash at the beginning.
A RenderFlex overflowed by 99804 pixels on the bottom.
The relevant error-causing widget was:
Column file:///E:/FlutterProjects/myproject/lib/builders/CustomPageView.dart:47:26
Here's the code. Line 47 is the first child: column.
class _CustomPageViewState extends State<CustomPageView> {
Widget build(context) {
return PageView.builder(
itemCount: widget.speakcrafts.length,
itemBuilder: (context, int currentIndex) {
return createViewItem(widget.speakcrafts[currentIndex], context);
},
);
}
Widget createViewItem(SpeakContent speakcraft, BuildContext context) {
var contsize = MediaQuery.of(context).size.width * 0.60;
var contHeightsize = MediaQuery.of(context).size.height;
return Stack(
children: <Widget>[
Container(
color: Colors.black12,
child: Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(20.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Image.network(
speakcraft.gavatar,
height: contsize,
width: contsize,
),
PlayerWidget2(url: kUrl),
],
),
),
],
),
),
],
);
And here's the full error code with chunhunghan's ConstrainedBox suggestion;
A RenderFlex overflowed by 99325 pixels on the right.
The relevant error-causing widget was:
Row file:///E:/FlutterProjects/speakoholic/lib/builders/CustomPageView.dart:121:25
The specific RenderFlex in question is: RenderFlex#d5393 relayoutBoundary=up8 OVERFLOWING
parentData: offset=Offset(0.0, 556.9); flex=null; fit=null (can use size)
constraints: BoxConstraints(0.0<=w<=674.9, 0.0<=h<=Infinity)
size: Size(674.9, 100000.0)
direction: horizontal
mainAxisAlignment: center
mainAxisSize: max
crossAxisAlignment: center
textDirection: ltr
verticalDirection: down
child 1: RenderErrorBox#d3900
parentData: offset=Offset(0.0, 0.0); flex=null; fit=null (can use size)
constraints: BoxConstraints(unconstrained)
size: Size(100000.0, 100000.0)
════════════════════════════════════════════════════════════════════════════════════════════════════
════════ Exception caught by rendering library ═════════════════════════════════════════════════════
A RenderFlex overflowed by 100385 pixels on the bottom.
The relevant error-causing widget was:
Column file:///E:/FlutterProjects/speakoholic/lib/builders/CustomPageView.dart:49:28

It turns out I had to follow the error further down the widget tree of this widget;
child: PlayerWidget2(url: kUrl))
Within PlayerWidget2 was a path that was null prior to a PageViewBuilder being built. This threw a null path error which lead to the renderflex error. Once built, the null was filled in with a path. So in order to get rid of the errors I simply added a default path to the widget to fill in the null until the PageViewBuilder was built.

you can wrap your whole body content as a child of SingleChildScrollView SinglechildScrollView widget which may help you to overcome from this issue,or you can also make use of listview which can arrange list of widgets properly ListView

Related

Image overflows in columns for a split second

Here is my code:
AlertDialog alert = AlertDialog(
content: Container(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Image(
image: correct
? AssetImage('assets/images/correct.png')
: AssetImage('assets/images/wrong.png')),
Padding(padding: EdgeInsets.fromLTRB(0.0, 10.0, 0.0, 0.0)),
Text(message)
],
),
),
actions: [
okButton,
],
);
So, it almost works as expected. When I call the alert dialog, it appears correctly with the image and the text. But, for a split second, something overflows.
Here is the stack:
════════ Exception caught by rendering library
═════════════════════════════════════════════════════ The following
assertion was thrown during layout: A RenderFlex overflowed by 102
pixels on the bottom.
The relevant error-causing widget was: Column
file:///Users/path/to/file/blabla.dart:61:16
: To inspect this widget in Flutter DevTools, visit:
http://127.0.0.1:9100/#/inspector?uri=http%3A%2F%2F127.0.0.1%3A55261%2FDahKsJWBhm4%3D%2F&inspectorRef=inspector-863
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#117f5
relayoutBoundary=up9 OVERFLOWING ... parentData: offset=Offset(24.0,
20.0) (can use size) ... constraints: BoxConstraints(w=192.0, 0.0<=h<=120.0) ... size: Size(192.0, 120.0) ... direction: vertical ... mainAxisAlignment: start ... mainAxisSize: min ...
crossAxisAlignment: center ... verticalDirection: down
◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤
Any idea what might cause this? Thx!
Wrapping your Column with SingleChildScrollView might fix the problem:
AlertDialog alert = AlertDialog(
content: Container(
child: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Image(
image: correct
? AssetImage('assets/images/correct.png')
: AssetImage('assets/images/wrong.png')),
Padding(padding: EdgeInsets.fromLTRB(0.0, 10.0, 0.0, 0.0)),
Text(message)
],
),
),
),
actions: [
okButton,
],
);

RenderFlex error in flutter after a stateful widget is called inside a singlechildscrollview column

This is the likes Widget which shows likes. It is called inside a scrollview column of another dart file. Everything was working fine before this widget's addition
#override
Widget build(BuildContext context) {
return Container(
height: 100,
child: Row(
children: <Widget>[
Expanded(
child: ListTile(
leading: IconButton(
icon: likedByReader
? Icon(Icons.favorite, color: Colors.orange)
: Icon(Icons.favorite, color: Colors.grey),
onPressed: _pressed,
),
),
),
Expanded(
child: Text('${likesList.length} likes'),
)
],
),
);
}
This is how LikeWidget is called
Expanded(child: LikeWidget(widget.readerEmail, widget.blogUIDInFirebase),),
Error shown in the console
RenderFlex children have non-zero flex but incoming height constraints are unbounded.
RenderBox was not laid out: _RenderSingleChildViewport#89f28 relayoutBoundary=up10 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
'package:flutter/src/rendering/box.dart':
Failed assertion: line 1694 pos 12: 'hasSize'
You can't use Expanded inside a SingleChildScrollView. since the SingleChildScrollView has special constraints and Expanded it's expecting to be used inside a Column or Row .
There is a similar question here , and basically you should do conditional rendering for this to work, return a column when the content height is smaller than the parent height, and return a scrollview when the content doesn't fit .For this i would use a LayoutBuilder, but a CustomScrollView seems to be more performant Check the answers of that question.

Renderflex overflowed at bottom

I am trying to do animation where the HomePageTop widget shrinks whenever i scroll the listview and
the offset of listview is greater than > 100.
The animation works but just at the end of the animation renderflex overflowed error is being shown.
class HomePageView extends StatefulWidget {
#override
_HomePageViewState createState() => _HomePageViewState();
}
class _HomePageViewState extends State<HomePageView> {
ScrollController scrollController = ScrollController();
bool closeTopContainer = false;
#override
void initState() {
super.initState();
scrollController.addListener(() {
setState(() {
closeTopContainer = scrollController.offset > 100;
});
});
}
#override
Widget build(BuildContext context) {
final Size size = MediaQuery.of(context).size;
return Scaffold(
backgroundColor: Color.fromRGBO(235, 236, 240, 1),
body: Container(
height: size.height,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
AnimatedContainer(
color: Colors.redAccent,
width: size.width,
duration: const Duration(milliseconds: 200),
height: closeTopContainer ? 0 : size.width * .33,
child: HomePageTop(
size: size,
)),
Expanded(
child: ListView(
controller: scrollcontroller),
],
),
),
);
}
}
Here the size of animated container is being controlled by listview scroll controller.
whenever i scroll down this error is being given
Error
The following assertion was thrown during layout:
A RenderFlex overflowed by 5.4 pixels on the bottom.
The relevant error-causing widget was:
Column file:///D:/flutter/app/app/lib/views/Widgets/widgets.dart:94:12
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.
The specific RenderFlex in question is: RenderFlex#a37e0 OVERFLOWING:
needs compositing
creator: Column ← HomePageTop ← DecoratedBox ← ConstrainedBox ← Container ← AnimatedContainer ← Flex
← ConstrainedBox ← Container ← _BodyBuilder ← MediaQuery ← LayoutId-[<_ScaffoldSlot.body>] ← ⋯
parentData: <none> (can use size)
constraints: BoxConstraints(w=470.2, h=49.6)
size: Size(470.2, 49.6)
direction: vertical
mainAxisAlignment: start
mainAxisSize: min
crossAxisAlignment: center
verticalDirection: down
My HomePageTop widget
Widget build(BuildContext context) {
return Column(
children: [
SizedBox(
height: 55,
),
Expanded(
child: Stack(children: [
Positioned(right: 20, child: FittedBox(fit:BoxFit.fill,child: LogoutButton())),
Positioned(
top: 50,
child: Container(
alignment: Alignment.topCenter,
padding: EdgeInsets.all(20),
width: size.width,
child: searchField())),
]),
),
],
);
}
Wrapping the animated container with expanded removes the error but the animation where size decreases does not occur.
searchField() is a text field.Wrapping it in a fitted box also gives an error.
Any help is appreciated.Thanks in advance
It is because the SizedBox inside HomePageTop widget has a fixed height. If you remove it the error does not appear, you don't need it anyway.

Flutter Web: Overflow issue in bottom

Code: Basically I have a simple app with three images aligned. I have 1 column and two rows. First row has two images and second row has 1 image aligned. Its the structure of the app. It just aligns perfectly when run below code in device but the moment I run on WEB there is this overflow. I try resizing the browser window only then it begins to become pretty again. Is there a workaround for Flutter Web please on how should I do the alignments here? Below code is inside body and inside Scaffold. I am attaching pics from device where there is no issue and from Flutter web where there is overflow issue.
return Column(
mainAxisAlignment: MainAxisAlignment.center,
//crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Row(
children: <Widget>[
Expanded(
child: FlatButton(
child: Image.asset('images/image1.png'),
),
),
Expanded(
child: FlatButton(
child: Image.asset('images/image1.png'),
),
),
],
),
Row(
children: <Widget>[
Expanded(
child: Image.asset('images/image1.png'),
),
],
),
],
);
}
Error:
══╡ EXCEPTION CAUGHT BY RENDERING LIBRARY
╞═════════════════════════════════════════════════════════ The
following assertion was thrown during layout: A RenderFlex overflowed
by 1238 pixels on the bottom.
The relevant error-causing widget was: Column
file:///C:/Users/1025632/Documents/GitHub/flutter-course/diceylips/lib/main.dart:43:12
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#1ad1e
relayoutBoundary=up1 OVERFLOWING: creator: Column ← DicePage ←
_BodyBuilder ← MediaQuery ← LayoutId-[<_ScaffoldSlot.body>] ←
CustomMultiChildLayout ← AnimatedBuilder ← DefaultTextStyle ← AnimatedDefaultTextStyle ←
_InkFeatures-[GlobalKey#cb60e ink renderer] ← NotificationListener ←
PhysicalModel ← ⋯ parentData: offset=Offset(0.0, 56.0); id=_ScaffoldSlot.body (can use size) constraints:
BoxConstraints(0.0<=w<=1280.0, 0.0<=h<=554.0) size: Size(1280.0,
554.0)
direction: vertical
mainAxisAlignment: center
mainAxisSize: max
crossAxisAlignment: center
verticalDirection: down
Image with no issue in device
Image with overflow issue in chrome
Wrap the column with a sized box or container with defined height and width
SizedBox(
height:200,
width:200,
child: your column goes here,
)
Add below code inside Container
Container(
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height,
....
....
)
This is the generic way to define full width and height to your Container
If you don't try to fit your widget in screen and scroll is an option for you, you can use listview or a similar widget.
ListView(
children: <Widget>[
Column(
Otherwise, wrapping Container with MediaQuery.of(context).size.width and MediaQuery.of(context).size.height will work but there is just one catch here, if you use an appbar this height should be "MediaQuery.of(context).size.height - AppBar().preferredSize.height"

How to use Expanded in SingleChildScrollView?

How to use Expanded in SingleChildScrollView? I have a screen with Image.network, ListView.builder and Row (TextFormField and IconButton). I wrapped ListView with Expanded. How to wrap this column with SingleChildScrollView? I need to move screen when the keyboard is open to see what I am writing. When I wrap my column I have this error.
body: SingleChildScrollView(
child: Column(
children: <Widget>[
Container(
child: GestureDetector(
child:
Image.network(
postOne.imageUrl,
fit: BoxFit.fitWidth,
height: MediaQuery
.of(context)
.size
.width,
width: MediaQuery
.of(context)
.size
.width,
),
onLongPress: () {},
onDoubleTap: () {},
),
),
Expanded(
//height: MediaQuery.of(context).size.width*0.33,
child: ListView.builder(
itemCount: commentList.length,
itemBuilder: (context, position) {
return GestureDetector(
onLongPress: () {},
child: Card(
child: Padding(
padding: EdgeInsets.all(5.0),
child: new CheckboxListTile(
title: new Text(commentList
.elementAt(position)
.coment,
style: TextStyle(fontSize: 18.0),),
value: values[commentList
.elementAt(position)
.coment],
onChanged: (bool value) {}),
),
)
);
}
),
),
Container(
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
new Flexible(
child: Theme(
data: new ThemeData(
brightness: Brightness.light,
primarySwatch: Colors.grey,
inputDecorationTheme: new InputDecorationTheme(
labelStyle: new TextStyle(
color: Colors.black45, fontSize: 18.0
),
)
),
child: new Form(
key: _formKey,
child: new TextFormField(
validator: (value) {
if (value.isEmpty) {
return 'Please enter the comment';
}
},
controller: commentController,
decoration: new InputDecoration(
labelText: "Add comment",
//hintText: 'Add comment'
),
keyboardType: TextInputType.text,
),
),
),
),
new Container(
margin: EdgeInsets.only(left: 10.0, top: 12.0),
child: new IconButton(
icon: new Icon(Icons.send, color: Colors.black,),
onPressed: () {}
)
),
]),
),
],
),
),
I/flutter ( 6816): ══╡ EXCEPTION CAUGHT BY RENDERING LIBRARY ╞═════════════════════════════════════════════════════════
I/flutter ( 6816): The following assertion was thrown during performLayout():
I/flutter ( 6816): RenderFlex children have non-zero flex but incoming height constraints are unbounded.
I/flutter ( 6816): When a column is in a parent that does not provide a finite height constraint, for example if it is
I/flutter ( 6816): in a vertical scrollable, it will try to shrink-wrap its children along the vertical axis. Setting a
I/flutter ( 6816): flex on a child (e.g. using Expanded) indicates that the child is to expand to fill the remaining
I/flutter ( 6816): space in the vertical direction.
I/flutter ( 6816): These two directives are mutually exclusive. If a parent is to shrink-wrap its child, the child
I/flutter ( 6816): cannot simultaneously expand to fit its parent.
I/flutter ( 6816): Consider setting mainAxisSize to MainAxisSize.min and using FlexFit.loose fits for the flexible
I/flutter ( 6816): children (using Flexible rather than Expanded). This will allow the flexible children to size
I/flutter ( 6816): themselves to less than the infinite remaining space they would otherwise be forced to take, and
I/flutter ( 6816): then will cause the RenderFlex to shrink-wrap the children rather than expanding to fit the maximum
I/flutter ( 6816): constraints provided by the parent.
I/flutter ( 6816): The affected RenderFlex is:
I/flutter ( 6816): RenderFlex#9f534 relayoutBoundary=up11 NEEDS-LAYOUT NEEDS-PAINT
I/flutter ( 6816): The creator information is set to:
I/flutter ( 6816): Column ← _SingleChildViewport ← IgnorePointer-[GlobalKey#3670d] ← Semantics ← Listener ←
I/flutter ( 6816): _GestureSemantics ← RawGestureDetector-[LabeledGlobalKey<RawGestureDetectorState>#4878e] ←
I/flutter ( 6816): Listener ← _ScrollableScope ← _ScrollSemantics-[GlobalKey#c5885] ← RepaintBoundary ← CustomPaint ←
I/flutter ( 6816): ⋯
I/flutter ( 6816): The nearest ancestor providing an unbounded width constraint is:
I/flutter ( 6816): _RenderSingleChildViewport#155d8 relayoutBoundary=up10 NEEDS-LAYOUT NEEDS-PAINT
I/flutter ( 6816): creator: _SingleChildViewport ← IgnorePointer-[GlobalKey#3670d] ← Semantics ← Listener ←
I/flutter ( 6816): _GestureSemantics ← RawGestureDetector-[LabeledGlobalKey<RawGestureDetectorState>#4878e] ←
I/flutter ( 6816): Listener ← _ScrollableScope ← _ScrollSemantics-[GlobalKey#c5885] ← RepaintBoundary ← CustomPaint ←
I/flutter ( 6816): RepaintBoundary ← ⋯
I/flutter ( 6816): parentData: <none> (can use size)
I/flutter ( 6816): constraints: BoxConstraints(0.0<=w<=440.8, 0.0<=h<=649.3)
I/flutter ( 6816): size: MISSING
I/flutter ( 6816): See also: https://flutter.dev/layout/
I/flutter ( 6816): If this message did not help you determine the problem, consider using debugDumpRenderTree():
I/flutter ( 6816): https://flutter.dev/debugging/#rendering-layer
I/flutter ( 6816): http://docs.flutter.io/flutter/rendering/debugDumpRenderTree.html
I/flutter ( 6816): If none of the above helps enough to fix this problem, please don't hesitate to file a bug:
I/flutter ( 6816): https://github.com/flutter/flutter/issues/new?template=BUG.md
I/flutter ( 6816):
Instead of using SingleChildScrollView, It's easier to use CustomScrollView with a SliverFillRemaining.
Try this:
CustomScrollView(
slivers: [
SliverFillRemaining(
hasScrollBody: false,
child: Column(
children: <Widget>[
const Text('Header'),
Expanded(child: Container(color: Colors.red)),
const Text('Footer'),
],
),
),
],
)
Try this,
LayoutBuilder(
builder: (context, constraint) {
return SingleChildScrollView(
child: ConstrainedBox(
constraints: BoxConstraints(minHeight: constraint.maxHeight),
child: IntrinsicHeight(
child: Column(
children: <Widget>[
Text("Header"),
Expanded(
child: Container(
color: Colors.red,
),
),
Text("Footer"),
],
),
),
),
);
},
)
I got this solution from git issues when I get into the same situation. I don't have the git link. I think it may help you.
Reusable widget:
Note: use it, only if one of the children is Expanded
import 'package:flutter/material.dart';
class ScrollColumnExpandable extends StatelessWidget {
final List<Widget> children;
final CrossAxisAlignment crossAxisAlignment;
final MainAxisAlignment mainAxisAlignment;
final VerticalDirection verticalDirection;
final TextDirection textDirection;
final TextBaseline textBaseline;
final EdgeInsetsGeometry padding;
const ScrollColumnExpandable({
Key key,
this.children,
CrossAxisAlignment crossAxisAlignment,
MainAxisAlignment mainAxisAlignment,
VerticalDirection verticalDirection,
EdgeInsetsGeometry padding,
this.textDirection,
this.textBaseline,
}) : crossAxisAlignment = crossAxisAlignment ?? CrossAxisAlignment.center,
mainAxisAlignment = mainAxisAlignment ?? MainAxisAlignment.start,
verticalDirection = verticalDirection ?? VerticalDirection.down,
padding = padding ?? EdgeInsets.zero,
super(key: key);
#override
Widget build(BuildContext context) {
final children = <Widget>[const SizedBox(width: double.infinity)];
if (this.children != null) children.addAll(this.children);
return LayoutBuilder(
builder: (context, constraint) {
return SingleChildScrollView(
child: Padding(
padding: padding,
child: ConstrainedBox(
constraints: BoxConstraints(
minHeight: constraint.maxHeight - padding.vertical,
),
child: IntrinsicHeight(
child: Column(
crossAxisAlignment: crossAxisAlignment,
mainAxisAlignment: mainAxisAlignment,
mainAxisSize: MainAxisSize.max,
verticalDirection: verticalDirection,
children: children,
textBaseline: textBaseline,
textDirection: textDirection,
),
),
),
),
);
},
);
}
}
The answer is in the error itself. When the column is inside a view that is scrollable, the column is trying to shrink-wrap its content but since you used Expanded as a child of the column it is working opposite to the column trying to shrink-wrap its children. This is causing this error because these two directives are completely opposite to each other.
As mentioned in the error logs try the following:
Consider setting mainAxisSize to MainAxisSize.min (for column) and using FlexFit.loose fits for the flexible(use Flexible rather than Expanded).
I tried Vijaya Ragavan solution but did some adjustments to it & it still works.
To use Expanded with SingleChildScrollView, I used ConstrainedBox and set its height to the height of the screen (using MediaQuery). You'll just need to make sure the screen content you put inside ConstrainedBox is not bigger than the height of the screen.
Otherwise set the height of ConstrainedBox to height of the content you want to display on the screen.
SingleChildScrollView(
child: ConstrainedBox(
constraints: BoxConstraints(maxHeight: MediaQuery.of(context).size.height),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Expanded(
child: Text('Hello World!'),
),
],
),
)
)
Edit:
To subtract the height of the AppBar and/or the Status Bar, see below:
double screenHeightMinusAppBarMinusStatusBar = MediaQuery.of(context).size.height
- appBar.preferredSize.height
- MediaQuery.of(context).padding.top;
Simply wrap your SingleChildScrollView in a Center or an Align element.
Example :
Align(
alignment: Alignment.topCenter,
child: SingleChildScrollView(
child: Column(
children: <Widget>[
...
]
}
}
}
or
Center(
child: SingleChildScrollView(
child: Column(
children: <Widget>[
...
]
}
}
}
You can simply wrap the column in a sized box and give it a width and height as shown:
SingleChildScrollView(
child: SizedBox(
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height * 0.9,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Container() //widget here
const Expanded(
child: SizedBox(),
),
Container() //widget here
],
),
As already pointed out, because you are using a scrollable, you can't expand to the infinity (theoretically speaking), that's what's happening when you try to expand your ListView that is nested in a SingleChildScrollView.
You can try using a NestedScrollView, or, if it fits your demands and because you have commented out this line:
//height: MediaQuery.of(context).size.width*0.33,
You can just wrap your ListView in a ConstrainedBox (or even just a regular Container) with that height, for example, instead of the Expanded, like so:
Container(
height: MediaQuery.of(context).size.width*0.33,
child: ListView.builder(
itemCount: commentList.length,
...
)
)
Since you are already in a scrollable, you shouldn't have issues with smaller screens, because the whole tree is scrollable.
The trick is to only apply the ScrollView when you need to, and otherwise to let the content expand.
Something like this works well:
class ConstrainedFlexView extends StatelessWidget {
final Widget child;
final double minSize;
final Axis axis;
const ConstrainedFlexView(this.minSize, {Key key, this.child, this.axis}) : super(key: key);
bool get isHz => axis == Axis.horizontal;
#override
Widget build(BuildContext context) {
return LayoutBuilder(
builder: (_, constraints) {
double viewSize = isHz ? constraints.maxWidth : constraints.maxHeight;
if (viewSize > minSize) return child;
return SingleChildScrollView(
scrollDirection: axis ?? Axis.vertical,
child: ConstrainedBox(
constraints: BoxConstraints(
maxHeight: isHz ? double.infinity : minSize,
maxWidth: isHz ? minSize : double.infinity),
child: child,
),
);
},
);
}
}
Usage:
ConstrainedFlexView(600, child: FlexContent())
This will flex to fill all vertical space, but once the widget is <600px it will switch to a constrained box + scroll view, allowing the content not to be squished too much.
Most of the answers are not taken into account wich you have a textfield widget, so when the keyboard open you will get a problem with the size of your content (it will be heigher than the screen), so you should to wrap one of the widgets inside the (expanded) at least with (flexible).
Scaffold(
resizeToAvoidBottomInset: true,
body:CustomScrollView(
slivers: [
SliverFillRemaining(
hasScrollBody: false,
child: Column(
children: <Widget>[
const TextField(),
Expanded(
child: Column(
children: [
Flexible(child: someWidget()),
]
)
),
],
),
),
],
)
)
If what you want is:
Being able to use expanded inside the SingleChildScrollView to fill the remaining screen.
Not being bothered by the keyboard either hidding the TextFormField you are writing into either resizing the content of the SingleChildScrollView.
I had the same problem.
Here is a maybe hazardous but in my case working solution I used:
import 'package:flutter/material.dart';
class FiniteSizeSingleChildScrollViewNotBotheredByKeyboard
extends StatefulWidget {
final Widget child;
const FiniteSizeSingleChildScrollViewNotBotheredByKeyboard(
{Key? key, required this.child})
: super(key: key);
#override
State<FiniteSizeSingleChildScrollViewNotBotheredByKeyboard> createState() =>
_FiniteSizeSingleChildScrollViewNotBotheredByKeyboardState();
}
class _FiniteSizeSingleChildScrollViewNotBotheredByKeyboardState
extends State<FiniteSizeSingleChildScrollViewNotBotheredByKeyboard> {
double width = 0, height = 0;
#override
Widget build(BuildContext context) {
return LayoutBuilder(builder: (context, constraints) {
if (width != constraints.maxWidth) {
width = constraints.maxWidth;
height = constraints.maxHeight;
}
return SingleChildScrollView(
child: SizedBox(
width: width,
height: height,
child: widget.child,
),
);
});
}
}
The idea is to get the available size just before the SingleChildScrollView, and then to inject this size into a SizedBox which is inside the SingleChildScrollView. Also, to avoid the keyboard changing this size, there is a if condition which prevents changing the height if the width has not changed.
The only issue I uncontered yet with this custom widget, is that if a TextFormField controller inside this widget (lets call it widget A) call setState on a widget B containing this widget A which itself is a child of the keyed Form associated with the TextFormField, The contoller will trigger a rebuild at the same time as the keyboard will trigger a rebuild of the widget A, which generate an exception. To avoid this put the keyed Form inside the widget A (and not above).
I ran into the problem that a widget within the sub tree of the SliverFillRemaining / IntrinsicHeight was using a LayoutBuilder. And LayoutBuilder cannot be used in any widget tree that calculates its intrinsic dimensions (You will get an error saying that LayoutBuilder does not support returning intrinsic dimensions).
Since SliverFillRemaining with hasScrollBody: false also calculates the intrinsic dimensions of its child, it cannot be combined with any descendant widget that uses LayoutBuilder.
It is therefore not possible to combine both options in the same widget sub tree.
If your layout, however, does not use LayoutBuilder as a descendant of the SliverFillRemaining / IntrinsicHeight widget, but somewhere else in the scroll view, you can simply put it in a different sliver. Example reusing tanghao's code could look like this:
CustomScrollView(
slivers: [
// Use SliverList or any different sliver to display the children that use LayoutBuilder
SliverList(
delegate: SliverChildListDelegate(childrenContainingLayoutBuilder),
),
// Use the SliverFillRemaining for the sub tree that uses Expanded / Flexible / Spacer etc.
SliverFillRemaining(
hasScrollBody: false,
child: Column(
children: <Widget>[
const Text('Header'),
Expanded(child: Container(color: Colors.red)),
const Text('Footer'),
],
),
),
],
)