Flutter SingleChildScrollView(Horizontal) within another SingleChildScrollView(Vertical) - flutter

How can I make the Flutter SingleChildScrollView(Horizontal) within another SingleChildScrollView(Vertical) code attached here below work?
I am getting the following exception:
Unhandled Exception: Cannot hit test a render box with no size.
The hitTest() method was called on this RenderBox: _RenderScrollSemantics#0e053:
needs compositing
creator: _ScrollSemantics-[GlobalKey#35899] ← Scrollable ← SingleChildScrollView ← ColoredBox ← ConstrainedBox ← Container ← Column ← _SingleChildViewport ← IgnorePointer-[GlobalKey#364d1] ← Semantics ← Listener ← _GestureSemantics ← ⋯
parentData: (can use size)
constraints: BoxConstraints(w=414.0, h=896.0)
semantic boundary
size: MISSING
Although this node is not marked as needing layout, its size is not set.
A RenderBox object must have an explicit size before it can be hit-tested. Make sure that the RenderBox in question sets its size during layout.
#0 RenderBox.hitTest. (package:flutter/src/rendering/box.dart:2386:9)
#1 RenderBox.hitTest (package:flutter/src/rendering/box.dart:2401:6)
#2 RenderProxyBoxMixin.hitTestChildren (p<…>
[VERBOSE-2:ui_dart_state.cc(177)] Unhandled Exception: Cannot hit test a render box with no size.
The hitTest() method was called on this RenderBox: _RenderScrollSemantics#0e053:
needs compositing
creator: _ScrollSemantics-[GlobalKey#35899] ← Scrollable ← SingleChildScrollView ← ColoredBox ← ConstrainedBox ← Container ← Column ← _SingleChildViewport ← IgnorePointer-[GlobalKey#364d1] ← Semantics ← Listener ← _GestureSemantics ← ⋯
parentData: (can use size)
constraints: BoxConstraints(w=414.0, h=896.0)
semantic boundary
size: MISSING
Although this node is not marked as needing layout, its size is not set.
A RenderBox object must have an explicit size before it can be hit-tested. Make sure that the RenderBox in question sets its size during layout.
#0 RenderBox.hitTest. (package:flutter/src/rendering/box.dart:2386:9)
#1 RenderBox.hitTest (package:flutter/src/rendering/box.dart:2401:6)
#2 RenderProxyBoxMixin.hitTestChildren (p<…>
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
void main() => runApp(
MaterialApp(
home: HomeScreen(),
),
);
class HomeScreen extends StatelessWidget {
#override
Widget build(BuildContext context) {
SizeConfig().init(context);
return Scaffold(
appBar: AppBar(
title: Text('Grid Demo'),
),
body: SingleChildScrollView(
scrollDirection: Axis.vertical,
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: [
Container(
width: SizeConfig.screenWidth,
height: SizeConfig.screenHeight,
color: Colors.grey[200],
child: SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Grid(),
),
),
SizedBox(
height: 50,
),
Container(color: Colors.grey, height: 200),
],
),
),
);
}
}
class Grid extends StatelessWidget {
List<Positioned> getUnits() {
double _unitRadius = 50;
List<Positioned> _units = [];
double _leftCoordinate = 0;
double _bottomCoordinate = 0;
double _margin = 5;
double _stepFromLeft = _unitRadius + _margin;
double _stepFromBottom = _unitRadius + _margin;
int _maxColumns = 10;
int _maxRows = 10;
for (int i = 0; i < _maxRows; i++) {
for (int j = 0; j < _maxColumns; j++) {
_units.add(Positioned(
bottom: _bottomCoordinate,
left: _leftCoordinate,
child: Container(
width: _unitRadius,
height: _unitRadius,
decoration: BoxDecoration(
color: Colors.green,
),
child: Center(child: Text('$i $j')),
)));
_leftCoordinate += _stepFromLeft;
}
_leftCoordinate = 0;
_bottomCoordinate += _stepFromBottom;
}
return _units;
}
#override
Widget build(BuildContext context) {
return Stack(
children: getUnits(),
);
}
}
class SizeConfig {
static MediaQueryData _mediaQueryData;
static double screenWidth;
static double screenHeight;
static double blockSizeHorizontal;
static double blockSizeVertical;
static double _safeAreaHorizontal;
static double _safeAreaVertical;
static double safeBlockHorizontal;
static double safeBlockVertical;
void init(BuildContext context) {
_mediaQueryData = MediaQuery.of(context);
screenWidth = _mediaQueryData.size.width;
screenHeight = _mediaQueryData.size.height;
blockSizeHorizontal = screenWidth;
blockSizeVertical = screenHeight;
_safeAreaHorizontal =
_mediaQueryData.padding.left + _mediaQueryData.padding.right;
_safeAreaVertical =
_mediaQueryData.padding.top + _mediaQueryData.padding.bottom;
safeBlockHorizontal = (screenWidth - _safeAreaHorizontal);
safeBlockVertical = (screenHeight - _safeAreaVertical);
}
}

Try to put the vertical singlechildscrollview in a container, and set the width and height of this container to screen width and height. On the other hand it's more appropriate if you use ListView for horizontal scrolling, or ListView.builder if your items are of same types
ListView(
scrollDirection: Axis.horizontal,
shrinkWrap: true,
children: <Widget>[
//your widget items here
],
),

Here Your SingleChildScrollView items will scroll in vertically and ListView.builder items will draw items horizontally, (by default), in case of list view builder you need to fix a specific/dynamic height to avoid errors.
SingleChildScrollView(
child: Container(
height: 100,
child: ListView.builder(
itemBuilder: ...),
),
)
& in your code, use :
Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisSize: MainAxisSize.max,

Related

Flutter - Incorrect use of ParentDataWidget

Since I introduced a PageView widget, I get this error:
════════ Exception caught by widgets library ═══════════════════════════════════ The following assertion was thrown while applying parent data.: Incorrect use of ParentDataWidget.
The ParentDataWidget Expanded(flex: 1) wants to apply ParentData of type FlexParentData to a RenderObject, which has been set up to accept ParentData of incompatible type ParentData.
Usually, this means that the Expanded widget has the wrong ancestor RenderObjectWidget. Typically, Expanded widgets are placed directly inside Flex widgets. The offending Expanded is currently placed inside a RepaintBoundary widget.
The ownership chain for the RenderObject that received the incompatible parent data was: Padding ← Container ← AnimatedContainer-[LabeledGlobalKey<ImplicitlyAnimatedWidgetState<ImplicitlyAnimatedWidget>>#758ef] ← KeyboardAvoider ← Expanded ← VpFormContainer ← LoggedOutNickNamePage ← RepaintBoundary ← IndexedSemantics ← NotificationListener<KeepAliveNotification> ← ⋯ When the exception was thrown, this was the stack
#0 RenderObjectElement._updateParentData.<anonymous closure> package:flutter/…/widgets/framework.dart:5770
#1 RenderObjectElement._updateParentData package:flutter/…/widgets/framework.dart:5786
#2 RenderObjectElement.attachRenderObject package:flutter/…/widgets/framework.dart:5808
#3 RenderObjectElement.mount package:flutter/…/widgets/framework.dart:5501
#4 SingleChildRenderObjectElement.mount package:flutter/…/widgets/framework.dart:6117 ...
════════ Exception caught by widgets library ═══════════════════════════════════ The following assertion was thrown while applying parent data.: Incorrect use of ParentDataWidget.
The ParentDataWidget Expanded(flex: 1) wants to apply ParentData of type FlexParentData to a RenderObject, which has been set up to accept ParentData of incompatible type ParentData.
Usually, this means that the Expanded widget has the wrong ancestor RenderObjectWidget. Typically, Expanded widgets are placed directly inside Flex widgets. The offending Expanded is currently placed inside a RepaintBoundary widget.
The ownership chain for the RenderObject that received the incompatible parent data was: Padding ← Container ← AnimatedContainer-[LabeledGlobalKey<ImplicitlyAnimatedWidgetState<ImplicitlyAnimatedWidget>>#758ef] ← KeyboardAvoider ← Expanded ← VpFormContainer ← LoggedOutNickNamePage ← RepaintBoundary ← IndexedSemantics ← NotificationListener<KeepAliveNotification> ← ⋯ When the exception was thrown, this was the stack
#0 RenderObjectElement._updateParentData.<anonymous closure> package:flutter/…/widgets/framework.dart:5770
#1 RenderObjectElement._updateParentData package:flutter/…/widgets/framework.dart:5786
#2 RenderObjectElement.attachRenderObject package:flutter/…/widgets/framework.dart:5808
#3 RenderObjectElement.mount package:flutter/…/widgets/framework.dart:5501
#4 SingleChildRenderObjectElement.mount package:flutter/…/widgets/framework.dart:6117 ...
I have been trying fixes for the last couple of hours, but nothing is working. Does anyone know exactly where to apply a fix and what is the fix?
Here is the PageView:
class LoggedOutPageView extends StatelessWidget {
final _controller = PageController(
initialPage: 0,
);
#override
Widget build(BuildContext context) {
print('building loggedOutPageView');
final pageView = PageView(
physics: const NeverScrollableScrollPhysics(),
controller: _controller,
clipBehavior: Clip.none,
children: [
LoggedOutNickNamePage(_controller),
LoggedOutEmailPage(_controller),
LoggedOutPasswordPage(),
],
);
final _pageContent = Expanded(
child: Container(child: pageView, color: Colors.transparent), flex: 1);
final _pageIndicator = Container(
height: 50,
child: SmoothPageIndicator(
controller: _controller,
count: 3,
effect: const JumpingDotEffect(),
),
color: Colors.transparent);
return VpFormPageScaffold([
VpLogoHeader(
onPressed: () {
print(_controller.page);
if (_controller.page > 0) {
_controller.previousPage(
duration: const Duration(milliseconds: 800),
curve: Curves.easeInOutCubic);
} else {
Navigator.pop(context);
}
},
pop: false),
_pageContent,
_pageIndicator
]);
}
}
VpFormPageScaffold:
class VpFormPageScaffold extends StatelessWidget {
VpFormPageScaffold(this.children);
List<Widget> children;
#override
Widget build(BuildContext context) {
return Scaffold(
resizeToAvoidBottomPadding: false,
body: ConstrainedBox(
constraints: BoxConstraints.tightFor(
height: MediaQuery.of(context).size.height),
child: VpGradientContainer(
beginColor: initialGradientColor,
endColor: endGradientColor,
child: SafeArea(
child: Column(
mainAxisAlignment: MainAxisAlignment.end,
children: children)))));
}
}
VpGradientContainer:
class VpGradientContainer extends StatelessWidget {
const VpGradientContainer({this.child, this.beginColor, this.endColor});
final Widget child;
final Color beginColor;
final Color endColor;
#override
Widget build(BuildContext context) {
return Container(
child: child,
height: double.infinity,
width: double.infinity,
padding: const EdgeInsets.all(40),
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [beginColor, endColor],
),
),
);
}
}
Expanded widgets must be placed inside Flex widgets. You are using Expanded widget where it cannot be used. You'll have to remove Expanded widget from here :
final _pageContent = Expanded(
child: Container(child: pageView, color: Colors.transparent), flex: 1);
Please checkout Flutter docs for Expanded Widget:
Expanded
A widget that expands a child of a Row, Column, or Flex
so that the child fills the available space.
Using an Expanded widget makes a child of a Row, Column, or Flex
expand to fill the available space along the main axis (e.g.,
horizontally for a Row or vertically for a Column). If multiple
children are expanded, the available space is divided among them
according to the flex factor.
An Expanded widget must be a descendant of a Row, Column, or Flex, and
the path from the Expanded widget to its enclosing Row, Column, or
Flex must contain only StatelessWidgets or StatefulWidgets (not other
kinds of widgets, like RenderObjectWidgets).

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.

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'),
],
),
),
],
)

Overflow warning in AnimatedContainer adjusting height

Example
Using the CupertinoPicker, I want it to animate into view below a textinput, using the AnimatedContainer, but when it becomes visible, I get an overflow warning. From what I've seen you cannot adjust the size of the CupertinoPicker, only it's parent.
Is there a better solution?
Column(
children: <Widget>[
buildTextField(
field: 'limit',
label: 'How Many Guests?',
controller: TextEditingController(
text: eventModel.event['limit']),
onTap: () {
showPicker.value = !showPicker.value;
},
),
AnimatedContainer(
height: showPicker.value ? 150 : 0,
duration: Duration(milliseconds: 150),
child: showPicker.value
? CupertinoPicker(
backgroundColor: Colors.transparent,
itemExtent: 40,
children: List<Widget>.generate(
98,
(index) => Center(
child: Text(
'${index + 2}',
style: TextStyle(
color: Colors.black,
fontSize: 16),
),
),
),
onSelectedItemChanged: (item) {
print((item + 2).toString());
},
)
: null,
),
]
)
Exception:
flutter: ══╡ EXCEPTION CAUGHT BY RENDERING LIBRARY ╞═════════════════════════════════════════════════════════
flutter: The following message was thrown during layout:
flutter: A RenderFlex overflowed by 22 pixels on the bottom.
flutter:
flutter: The overflowing RenderFlex has an orientation of Axis.vertical.
flutter: The edge of the RenderFlex that is overflowing has been marked in the rendering with a yellow and
flutter: black striped pattern. This is usually caused by the contents being too big for the RenderFlex.
flutter: Consider applying a flex factor (e.g. using an Expanded widget) to force the children of the
flutter: RenderFlex to fit within the available space instead of being sized to their natural size.
flutter: This is considered an error condition because it indicates that there is content that cannot be
flutter: seen. If the content is legitimately bigger than the available space, consider clipping it with a
flutter: ClipRect widget before putting it in the flex, or using a scrollable container rather than a Flex,
flutter: like a ListView.
flutter: The specific RenderFlex in question is:
flutter: RenderFlex#73b9d relayoutBoundary=up16 OVERFLOWING
flutter: creator: Column ← Stack ← CupertinoPicker ← ConstrainedBox ← Container ← AnimatedContainer ←
flutter: Column ← Observer ← _FormScope ← WillPopScope ← Form ← Padding ← ⋯
flutter: parentData: not positioned; offset=Offset(0.0, 0.0) (can use size)
flutter: constraints: BoxConstraints(0.0<=w<=346.9, 0.0<=h<=18.2)
flutter: size: Size(346.9, 18.2)
flutter: direction: vertical
flutter: mainAxisAlignment: start
flutter: mainAxisSize: max
flutter: crossAxisAlignment: center
flutter: verticalDirection: down
flutter: ◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤
flutter: Another exception was thrown: A RenderFlex overflowed by 22 pixels on the bottom.
You can wrap your other widgets with a SingleChildScrollView as follows:
AnimatedContainer(
duration:Duration(milliseconds:500),
child: SingleChildScrollView(child:contents),
),
There is an issue with AnimatedContainer and the CupertinoPicker , because it's using a fixed height for the children itemExtent: 40 .
Try using SizeTransition to achieve the same effect. This is a sample :
class _MySampleWidgetState extends State<MySampleWidget>
with SingleTickerProviderStateMixin {
bool showPicker = false;
AnimationController _controller;
#override
void initState() {
_controller = AnimationController(
vsync: this,
duration: Duration(milliseconds: 200),
);
super.initState();
}
#override
void dispose() {
_controller.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
RaisedButton(
child: Text("text"),
onPressed: () {
showPicker = !showPicker;
if (showPicker) {
_controller.forward();
} else {
_controller.reverse();
}
},
),
SizeTransition(
sizeFactor: _controller,
child: Container(
height: 150,
child: CupertinoPicker(
backgroundColor: Colors.transparent,
itemExtent: 40,
children: List<Widget>.generate(
98,
(index) => Center(
child: Text(
'${index + 2}',
style: TextStyle(color: Colors.black, fontSize: 16),
),
)),
onSelectedItemChanged: (item) {
print((item + 2).toString());
},
),
),
),
],
),
);
}
}
you can use ClipRect, like this:
AnimatedContainer(
duration: Duration(milliseconds: 300),
height: size(_showAllEntitlements ? 400 : 180),
curve: Curves.easeInOutSine,
decoration: BoxDecoration(
color: ColorThemeData.color_grey19,
),
child: ClipRect(
child: Wrap(
children: [
Container(),
Container(),
Container(),
...
],
),
),
),

Flutter ListView crashes inside column

I need some help figuring out how I can render the ListView.
I have been following along a Flutter tutorial and I have had to stop because I can't get around this issue.
From what I can understand the ListView tries to take up an infinite amount of space which obviously crashes the app.
I have also come to understand the you can't have a ListView as a direct child of a Column/Row (I explain what I have tried to do about that below)
https://flutter.io/docs/development/ui/layout/box-constraints#flex
Here's the code:
#override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
Container(
margin: EdgeInsets.all(10),
child: ProductControl(_addProduct),
),
ListView.builder(
itemCount: _products.length,
itemBuilder: (BuildContext context, int index) => Card(
child: Column(
children: <Widget>[
Image.asset('assets/food.jpg'),
Text(_products[index])
],
),
),
)
],
);
}
This is what is being said in the beginning of the stacktrace:
flutter: ══╡ EXCEPTION CAUGHT BY RENDERING LIBRARY ╞═════════════════════════════════════════════════════════
flutter: The following assertion was thrown during performResize():
flutter: Vertical viewport was given unbounded height.
flutter: Viewports expand in the scrolling direction to fill their
container.In this case, a vertical
flutter: viewport was given an unlimited amount of vertical space in
which to expand. This situation
flutter: typically happens when a scrollable widget is nested inside
another scrollable widget.
flutter: If this widget is always nested in a scrollable widget there
is no need to use a viewport because
flutter: there will always be enough vertical space for the children.
In this case, consider using a Column
flutter: instead. Otherwise, consider using the "shrinkWrap" property
(or a ShrinkWrappingViewport) to size
flutter: the height of the viewport to the sum of the heights of its children.
And this is taken from the bottom of the stacktrace:
flutter: The following RenderObject was being processed when the
exception was fired:
flutter: RenderViewport#cab62 NEEDS-LAYOUT NEEDS-PAINT
flutter: creator: Viewport ← _ScrollableScope ← IgnorePointer-
[GlobalKey#b71f9] ← Semantics ← Listener ←
flutter: _GestureSemantics ← RawGestureDetector-
[LabeledGlobalKey<RawGestureDetectorState>#d0420] ←
flutter: _ScrollSemantics-[GlobalKey#02b55] ← Scrollable ←
PrimaryScrollController ← ListView ← Column ← ⋯
flutter: parentData: <none> (can use size)
flutter: constraints: BoxConstraints(0.0<=w<=375.0, 0.0<=h<=Infinity)
flutter: size: MISSING
flutter: axisDirection: down
flutter: crossAxisDirection: right
flutter: offset: ScrollPositionWithSingleContext#892dc(offset: 0.0,
range: null..null, viewport: null,
flutter: ScrollableState, AlwaysScrollableScrollPhysics ->
BouncingScrollPhysics, IdleScrollActivity#9455f,
flutter: ScrollDirection.idle)
flutter: anchor: 0.0
flutter: This RenderObject had the following descendants (showing up to
depth 5):
flutter: RenderSliverPadding#c8ab3 NEEDS-LAYOUT NEEDS-PAINT
flutter: RenderSliverList#66f1b NEEDS-LAYOUT NEEDS-PAINT
I have tried to wrap the ListView.builder in an Expanded widget but that doesn't work for me. (Which is what is being done in the tutorial)
I tried to wrap the Column in an IntrinsicHeight Widget with no success.
The only way I manage to get around this issue is by wrapping the ListView.builder in a Container widget with a set height property. But having to use a Container with a set height does not seem right to me.
I can try to post the full code to recreate this if needed.
try using 'Expanded' instead of Container or other layouts:
Column(
children: <Widget>[
Expanded(
//color: Colors.white,
child:
ListView.builder(
itemCount: list.length,
itemBuilder: (BuildContext context, int index) {
return ListTile(
contentPadding: EdgeInsets.all(10.0),
title: new Text('title'),
subtitle: new Text('sub title'),
onTap: () => clicked(list[index]['url']),
onLongPress: () => downloadAndStoreFile(list[index]['url'],
list[index]['name'], list[index]['title']),
);
}),
)
],
),
Add this to ListView.Builder =
#override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
Container(
margin: EdgeInsets.all(10),
child: ProductControl(_addProduct),
),
ListView.builder(
physics: NeverScrollableScrollPhysics(), ///
shrinkWrap: true, ///
scrollDirection: Axis.vertical, ///
itemCount: _products.length,
itemBuilder: (BuildContext context, int index) => Card(
child: Column(
children: <Widget>[
Image.asset('assets/food.jpg'),
Text(_products[index])
],
),
),
)
],
);
}
I think I managed to solve this as a last minute effort right after posting the question.
Something I didn't show in my question was another piece of code.
Basically this is what my code looked like.
body: Column(
children: <Widget>[
Column(
children: <Widget>[
Container(
margin: EdgeInsets.all(10),
child: ProductControl(_addProduct),
),
ListView.builder(
itemCount: _products.length,
itemBuilder: (BuildContext context, int index) => Card(
child: Column(
children: <Widget>[
Image.asset('assets/food.jpg'),
Text(_products[index])
],
),
),
)
],
),
],
),
The issue was that I had a Column with a Column as a direct child and apparently ListView does not like that.. So by removing the first Column I could then wrap my ListView in an Expanded widget and everything works. Maybe this can help someone else.
Both Column and ListView expands their size to maximum => Error
3 Solutions:
Wrap ListView with Expanded or Flexible
Column(
children: <Widget>[
Expanded(
child: ListView(),
)
],
)
Limit ListView height with Container or SizedBox
Column(
children: <Widget>[
Container(
height: 200,
child: ListView(),
)
],
)
My favorite solution: just add shrinkWrap and NeverScrollableScrollPhysics()
Column(
children: <Widget>[
ListView(
shrinkWrap: true,
physics: NeverScrollableScrollPhysics(),
)
],
)