Wrap class not wrapping widgets - flutter

I am dynamically generating Chip widgets but the Wrap class is not wrapping overflowing widgets to next line.
Widget build(BuildContext context) {
return Scaffold(
body: ListView(
physics: ClampingScrollPhysics(),
padding: const EdgeInsets.symmetric(
horizontal: 12,
),
children: [
Row(
children: [
Wrap(
spacing: 5,
children: _getChips(), // gets a list of chips
),
],
),
],
),
);
But I get this error in console
The following assertion was thrown during layout:
A RenderFlex overflowed by 94 pixels on the right.
The overflowing RenderFlex has an orientation of Axis.horizontal.
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.
Am I doing something wrong?

Try removing Row widget. Wrap with default direction is an alternative to Row that moves child widgets to the next line if there is no enough space.
Also, I'd recommend using SingleChildScrollView as a container instead of ListView to get scrolling behavior.
return Scaffold(
body: SingleChildScrollView(
physics: ClampingScrollPhysics(),
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 12,
),
child: Wrap(
spacing: 5,
children: _getChips(), // gets a list of chips
),
),
),
);

Related

How to display a screen which contains of an Icon on top half and ListView on bottom half?

I want to display a mock-up streaming screen like this:
Top half is the video player (showing the speaker), and bottom half is a ListView displaying participants/subscribers list.
Here's my code:
import 'package:flutter/material.dart';
import 'common.dart';
class StreamingView extends StatelessWidget {
// Display a Participant item
Widget getParticipantView(Participant item) {
return Container(
padding: EdgeInsets.all(10.0),
child: Column(
children: [
Align(
alignment: Alignment.centerLeft,
child: Text(
item.name,
style: TextStyle(fontSize: 14, color: Colors.black54),
),
),
Expanded(
child: CircleAvatar(backgroundColor: Colors.blue),
),
],
));
}
// Display the participants list on a ListView
Widget getParticipantsListView(List<Participant> participantsList){
//#override
// Widget build(BuildContext context) {
return Container (
//Expanded()
height: 40,
child: ListView.builder(
itemCount: participantsList.length,
itemBuilder: (context, index){
return getParticipantView(participantsList[index]);
}
)
);
//}
}
#override
Widget build(context) {
List<Participant> theList = [
Participant(name: "Jack", description:"Away"),
Participant(name:"Paul", description:"Available"),
Participant(name:"Clive", description:"Available"),
Participant(name:"Frank", description:"Available")
];
return Scaffold(
appBar: AppBar(),
body: Container(
padding: EdgeInsets.all(10.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Image.asset('assets/generic_portrait.jpg'),
Expanded(
flex: 1,
child: getParticipantsListView(theList)
),
],
)),
floatingActionButton: FloatingActionButton(
onPressed: () async {
print("The button is clicked...");
},
child: Icon(Icons.video_call)));
}
}
I ran it, and the result is this:
The speaker can be seen, but the participants list isn't. Turns out there's an exception:
══╡ 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. ... ... The relevant error-causing
widget was: Column
file:///C:/Users/anta40/Flutter/streamingtest/streaming.dart:11:16
That refers to child: Column( inside Widget getParticipantView().
How to fix this?
you can use stack , the parent maybe use column after that the stack will be the first , after that use a listview which can hold all the participants
Have you tried using Shrink-wrap in ListView.builder and remove the container with Static height.
The hight is unbound because you're using Expanded widget in the column. Remove the Expanded widget that is wrapping the CircleAvatar. Here's your code:
// Display a Participant item
Widget getParticipantView(Participant item) {
return Container(
padding: EdgeInsets.all(10.0),
child: Column(
children: [
Align(
alignment: Alignment.centerLeft,
child: Text(
item.name,
style: TextStyle(fontSize: 14, color: Colors.black54),
),
),
CircleAvatar(backgroundColor: Colors.blue),
],
));
}

Wrapping Expanded Widget in Padding Widget

While learning flutter, I was trying to add some padding to an Image widget which was wrapped inside an Expanded widget, my approach was to wrap the Expanded widget with a Padding widget, but as a result the image actually overflowed.
When I changed the code to wrapping the Image widget inside a Padding instead, it worked fine. So my question here is, why did the image overflow when I used the Padding on the Expanded widget instead of the image ? Is it not possible to do that in Flutter ?
I am pretty sure your issue was not overflowing of the Expanded widget when you wrapped it with Padding, but rather Flutter threw an Incorrect use of ParentDataWidget exception. That is because widgets like Expanded and Flexible has to be direct children of Column, Row or Flex widgets. That is why the only solution is to use the Padding over the child of Expanded.
Summarising, this code will not work:
Row(
children: const [
Padding(
padding: EdgeInsets.all(8.0),
child: Expanded(
child: Icon(Icons.icecream_outlined),
),
),
Text("SomeTextyTextHere"),
],
),
it will not work because Expanded has to be a direct child of Row.
This code however will work fine:
Row(
children: const [
Expanded(
child: Padding(
padding: EdgeInsets.all(8.0),
child: Icon(Icons.icecream_outlined),
),
),
Text("SomeTextyTextHere"),
],
),

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

Flutter error when wrapping a Positioned widget inside Stack and Column (A RenderFlex overflowed by Infinity pixels.)

I have a use case where I have to use Stack and Positioned to make some overlapping widgets. But I also have to wrap that inside a Column. When I do that then I get an error
A RenderFlex overflowed by Infinity pixels on the bottom.
A minimal example showing the issue:
import "package:flutter/material.dart";
class TestScreen extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text("Example"),
),
body: Column(
children: [
Stack(children: [
cardWidget(),
]),
],
),
),
);
}
Widget cardWidget() {
return Positioned(
left: 10.0,
child: Card(
color: Colors.green,
child: Container(
height: 200,
width: 100,
),
),
);
}
}
If I remove left: 10 then it works fine but thats not what I want.
The full error message (which I don't really understand):
The following assertion was thrown while applying parent data.:
Incorrect use of ParentDataWidget.
The ParentDataWidget Positioned(left: 10.0) wants to apply ParentData of type StackParentData to a
RenderObject, which has been set up to accept ParentData of incompatible type FlexParentData.
Usually, this means that the Positioned widget has the wrong ancestor RenderObjectWidget. Typically,
Positioned widgets are placed directly inside Stack widgets.
The offending Positioned is currently placed inside a Column widget.
The ownership chain for the RenderObject that received the incompatible parent data was:
Semantics ← Card ← Positioned ← Column ← _BodyBuilder ← MediaQuery ←
LayoutId-[<_ScaffoldSlot.body>] ← CustomMultiChildLayout ← AnimatedBuilder ← DefaultTextStyle ← ⋯
This is from the Flutter docs, for the Column class.
One common reason for this to happen is that the Column has been placed in another Column (without using Expanded or Flexible around the inner nested Column). When a Column lays out its non-flex children (those that have neither Expanded or Flexible around them), it gives them unbounded constraints so that they can determine their own dimensions (passing unbounded constraints usually signals to the child that it should shrink-wrap its contents). The solution in this case is typically to just wrap the inner column in an Expanded to indicate that it should take the remaining space of the outer column, rather than being allowed to take any amount of room it desires.
This is enough to understand what the problem is
The Column is giving the Stack unbounded constraints, due to which you're getting overflow error.
Putting it inside an Expanded widget however, solves it as Expanded is a flex-widget and it tries to cover entire available space. It then gives constraints to the Stack which prevents it from overflow.
Hope I helped.
Turns out I need to wrap my Stack with Expanded. Not sure why.
import "package:flutter/material.dart";
class TestScreen extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text("Example"),
),
body: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Flexible(
child: Stack(
children: [0, 1, 2, 3].map((e) => cardWidget(e)).toList(),
),
),
],
),
),
);
}
Widget cardWidget(int index) {
return Positioned(
left: index * 10.0,
child: Card(
elevation: 10,
color: Colors.green,
child: Container(
height: 200,
width: 100,
),
),
);
}
}
The issue with this solution is that it won't center my cards (neither horizontal or vertical). How is that achieved?
You can add symmetric Padding to the container to center the Stack. Also, add alignment: AlignmentDirectional.center to the Stack to center the widgets inside it(they will only be vertically centered, since they are Positioned widgets with left parameter provided).
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Flexible(
child: Container(
padding: EdgeInsets.symmetric(horizontal: 80.0),
child: Stack(
alignment: AlignmentDirectional.center,
children: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map((e) => cardWidget(e)).toList(),
),
),
),
],
),
);
}
Widget cardWidget(int index) {
return Positioned(
left: index * 50.0,
child: Card(
elevation: 10,
color: Colors.green,
child: Container(
height: 200,
width: 100,
),
),
);
}
Note: adjust the padding amount according to the cards' size and the screen size.
Result:

Two ListViews in the same column - Vertical viewport was given unbounded height [duplicate]

This is my code:
#override
Widget build(BuildContext context) {
return new Material(
color: Colors.deepPurpleAccent,
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
children:<Widget>[new GridView.count(crossAxisCount: _column,children: new List.generate(_row*_column, (index) {
return new Center(
child: new CellWidget()
);
}),)]
)
);
}
Exception as follows:
I/flutter ( 9925): ══╡ EXCEPTION CAUGHT BY RENDERING LIBRARY ╞═════════════════════════════════════════════════════════
I/flutter ( 9925): The following assertion was thrown during performResize():
I/flutter ( 9925): Vertical viewport was given unbounded height.
I/flutter ( 9925): Viewports expand in the scrolling direction to fill their container.In this case, a vertical
I/flutter ( 9925): viewport was given an unlimited amount of vertical space in which to expand. This situation
I/flutter ( 9925): typically happens when a scrollable widget is nested inside another scrollable widget.
I/flutter ( 9925): If this widget is always nested in a scrollable widget there is no need to use a viewport because
I/flutter ( 9925): there will always be enough vertical space for the children. In this case, consider using a Column
I/flutter ( 9925): instead. Otherwise, consider using the "shrinkWrap" property (or a ShrinkWrappingViewport) to size
I/flutter ( 9925): the height of the viewport to the sum of the heights of its children.
I/flutter ( 9925):
I/flutter ( 9925): When the exception was thrown, this was the stack:
I/flutter ( 9925): #0 RenderViewport.performResize.<anonymous closure> (package:flutter/src/rendering/viewport.dart:827:15)
I/flutter ( 9925): #1 RenderViewport.performResize (package:flutter/src/rendering/viewport.dart:880:6)
I/flutter ( 9925): #2 RenderObject.layout (package:flutter/src/rendering/object.dart:1555:9)
Adding this two lines
ListView.builder(
scrollDirection: Axis.vertical,
shrinkWrap: true,
...
This generally happens when you try to use a ListView/GridView inside a Column, there are many ways of solving it, I am listing few here.
Wrap ListView in Expanded
Column(
children: <Widget>[
Expanded( // wrap in Expanded
child: ListView(...),
),
],
)
Wrap ListView in SizedBox and give a bounded height
Column(
children: <Widget>[
SizedBox(
height: 400, // fixed height
child: ListView(...),
),
],
)
Use shrinkWrap: true in ListView.
Column(
children: <Widget>[
ListView(
shrinkWrap: true, // use this
),
],
)
So, everyone posted answers but no one cared to explain why:
I'll copy the documentation about shrinkWrap:
Whether the extent of the scroll view in the [scrollDirection] should be
determined by the contents being viewed.
If the scroll view does not shrink wrap, then the scroll view will expand
to the maximum allowed size in the [scrollDirection]. If the scroll view
has unbounded constraints in the [scrollDirection], then [shrinkWrap] must
be true.
Shrink wrapping the content of the scroll view is significantly more
expensive than expanding to the maximum allowed size because the content
can expand and contract during scrolling, which means the size of the
scroll view needs to be recomputed whenever the scroll position changes.
Defaults to false.
So, taking the vocabulary of the docs, what's happening here is that our ListView is in a situation of unbounded constraints (in the direction that we are scrolling), thus the ListView will complain that:
... a vertical viewport was given an unlimited amount of vertical space in
which to expand.
By simply setting shrinkWrap to true will make sure that it wraps its size defined by the contents. A sample code to illustrate:
// ...
ListView(
// Says to the `ListView` that it must wrap its
// height (if it's vertical) and width (if it's horizontal).
shrinkWrap: true,
),
// ...
That's what is going with your code, nonetheless, #Rémi suggestion is the best for this case, using Align instead of a Column.
put grid view inside Flexible or Expanded widget
return new Material(
color: Colors.deepPurpleAccent,
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
children:<Widget>[
Flexible(
child: GridView.count(crossAxisCount: _column,children: new List.generate(_row*_column, (index) {
return new Center(
child: new CellWidget(),
);
}),))]
)
);
Although shrinkWrap do the thing, but you can't scroll in ListView.
If you want scrolling functionality, you can add physics property:
ListView.builder(
scrollDirection: Axis.vertical,
shrinkWrap: true,
physics: ScrollPhysics(),
...
Cause of Viewport Exception
GridView / ListView grow until constraints (limits) stop this expansion & then scroll to view items beyond that size.
But Column lays out its children without any constraints, completely ignoring its own size and screen size. There is infinite space inside of Column.
Viewport was given unbounded height exception occurs because Grid/ListView expands to infinity inside a Column.
Flexible/Expanded exist to give Column children constraints based Column's size. (These two widgets cannot be used anywhere else, except inside Row and Column.)
Inside a Flexible/Expanded widget in Column, Grid/ListView only uses remaining space not taken by other, non-flexible widgets, which get laid out first. (See bottom for layout phases info.)
shrinkWrap is not a good solution
Using shrinkWrap: true on ListView inside a Column isn't really helpful as:
ListView no longer scrolls
ListView can still overflow
A ListView tall enough to show all of its items, will not scroll. Arguably defeats the purpose of using a ScrollView widget (parent class of ListView).
In Column layout phase 1 (see bottom for explanation of layout phases), ListView can be any height it wants (there are no constraints).
A ListView with shrinkWrap:true will grow in height to show all its items.
With enough items, a shrinkWrapped ListView will grow & grow (it never scrolls) to overflow whatever Column is inside, be it screen or other tighter constraint.
Shouldn't shrinkWrap just make ListView only as big as its items OR remaining space (up to screen height), and then scroll?
That would make intuitive sense, but inside a Column in phase 1 layout is done in unbounded space.
So, remaining space is unlimited/infinite. A max height is never reached. shrinkWrap:true just keeps growing Column height as items are added until overflowing the screen (or other smaller constraint).
Example shrinkWrap:true Overflow
Here's an example of adding items to a shrinkwrapped ListView in a Column until its height is taller than the screen, creating an overflow warning area:
(just keep pressing the + sign Floating Action Button)
import 'package:flutter/material.dart';
class ColumnListViewPage extends StatefulWidget {
#override
_ColumnListViewPageState createState() => _ColumnListViewPageState();
}
class _ColumnListViewPageState extends State<ColumnListViewPage> {
int _count = 0;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Column & ListView'),
),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add),
onPressed: () {
setState(() {
_count++;
});
},
),
body: SafeArea(
child: Container(
decoration: BoxDecoration(
border: Border.all(color: Colors.red)
),
/// // without center, Column will be as narrow as possible
alignment: Alignment.center,
/// Column is forced (constrained) to match screen dimension,
child: Column(
children: [
Text('Inner (Nested) Column'),
ListView.separated( // ← should be wrapped in Expanded
itemCount: _count,
separatorBuilder: (context, index) => const Divider(),
itemBuilder: (context, index) => Padding(
padding: const EdgeInsets.symmetric(vertical: 38.0),
child: Text('Row $index'),
),
shrinkWrap: true, // should be removed
)
],
),
),
),
);
}
}
For GridView/ListView in a Column, wrapping within Expanded or Flexible is likely the safest solution.
Expanded / Flexible
Expanded and Flexible can only be used inside Column (and its siblings like Row, etc.).
They must be used as immediate children of Column. We can't "nest" Expanded/Flexible in SizedBox or other widgets. Only directly under Column as immediate children.
Inside Column, placing ListView/GridView in Expanded or Flexible ensures it will use only available space, rather than infinite space.
Column
→ Expanded
→ ListView
ListView/GridView inside Expanded/Flexible in a Column doesn't need shrinkWrap because it is constrained (given a max. height) by the Expanded/Flexible widget. So when that constrained/defined height is used up, ListView/GridView will stop growing & begin scrolling.
Column Layout Phases
Column lays out children in 2 phases:
1st without constraints (unbounded space)
2nd with remaining space based on Column's parent
Phase 1
Any Column child not inside Flexible or Expanded will be laid out in phase 1, in infinite, limitless space completely ignoring screen size.
Widgets that need a vertical boundary/constraint to limit their growth (e.g. ListView) will cause a Vertical viewport was given unbounded height exception in phase 1 as there are no vertical bounds in unbounded space.
Most widgets have intrinsic size. Text for example, is only as high as its content & font size/style. It doesn't try to grow to fill a space. Defined-height widgets play well in Phase 1 of Column layout.
Phase 2
Any widget that grows to fill bounds, should be put in a Flexible or Expanded for Phase 2 layout.
Phase 2 calculates Column's remaining space from its parent constraints minus space used in Phase 1. This remaining space is provided to Phase 2 children as constraints.
ListView for example, will only grow to use remaining space & stop, avoiding viewport exceptions.
More info on Column layout algorithm and how Expanded works within it.
This situation typically happens when a scrollable widget is nested inside another scrollable widget.
In my case i use GridView inside of Column and that error throws.
GridView widget has shrinkWrap property/named parameter, to set it true my problem is fixed.
GridView.count(
shrinkWrap: true,
// rest of code
)
Don't use Column for single child alignment. Use Align instead.
new Align(
alignment: Alignment.topCenter,
child: new GridView(),
)
There are a lot of answer but each one have its own limitation. everyone is saying use shrinkWrap: true. Yes you should use it but the effect of these code is when you will scroll the list, it will automatically move to top item, means scroll back to top.
So perfect solution is use shrinkwrap with physics then only the list will be able to scroll smoothly.
shrinkWrap: true, //
physics: ScrollPhysics(), // both line is mandatory
If you want to see other example of Listview.builder with column as a child and list can be scroll vertically then you can see the example here - arrange multiple text in a vertical list.
Adding this two lines
ListView.builder(
scrollDirection: Axis.vertical,
shrinkWrap: true,
...
I wanted to post another answer because many answers (including the accepted one!) suggest using shrinkWrap: true in ListView.builder. While this removes the error, this solution is NOT ideal for performance reasons for this case. Flutter designed ListView with infinite size specifically to discourage this behaviour only when necessary!
Shrink wrapping the content of the scroll view is significantly more expensive than expanding to the maximum allowed size because the content can expand and contract during scrolling, which means the size of the scroll view needs to be recomputed whenever the scroll position changes.
In some cases/devices, this property caused glitchy scrolls and animation lag in my projects. Even if the lag isn't noticeable, this property does hinder scroll performance.
The OP shows that he is creating a small (finite) number of children for ListView. If we want to resolve the error for these lists, Google recommends using a Flexible widget, i.e. Expanded (a Flexible with flex 1) on the list itself.
Expanded(
child: ListView(
...
),
)
There are other layout issues here, but the vertical viewport unbounded height is because the ListView doesn't have a parent that bounds its size.
Two ways which we can solve the above issues
1. Using Flexible Widget,
The Flexible widget can be used inside Row, Column, and Flex.The flexibility to expand to fill the available space in the main axis (e.g., horizontally for a [Row] or vertically for a [Column])
But, remember, unlike Expanded, The Flexible widget does not require the child to fill available space. So, it's always better to use Flexible.
Column(
children: <Widget>[
Flexible(
child: ListView(...),
),
],
)
2. Using shrinkWrap: true
Using shrinkWrap as true, we tell the Listview to render its List to available space, not take below remaining screen.
Column(
children: <Widget>[
ListView(
shrinkWrap: true,
),
],
)
Also, physics attribute can be used to allow/disallow scrolling of Listview
Stop Scrolling
ListView(
shrinkWrap: true,
physics: NeverScrollableScrollPhysics(),
),
Allow Scrolling
ListView(
shrinkWrap: true,
physics: ScrollPhysics(),
),
I faced this problem because I wanted to display a GridView inside a ListView, and the solution was by adding the following not only in the ListView but also in the GridView as well:
shrinkwrap: true
scrollDirection: Axis.vertical
ListView.builder(
scrollDirection: Axis.vertical,
shrinkWrap: true,
itemCount: 10,
itemBuilder: (BuildContext context, int index) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: Container(
height: 100,
width: double.infinity,
color: Colors.pinkAccent,
),
);
},
),
If you still face this problem in 2021 ..here is the best and easy solution
ListView.builder(
scrollDirection: Axis.vertical,
shrinkWrap: true,
// itemExtent: 400, use this if you give hight of your items
physics: ScrollPhysics(),)
their are many solution .. but they have problem.. like when we use ListView and use its property shrinkWrap .then one thing you many notice the scroll does not work on listView so you must use physics: ScrollPhysics()
Container(
height: 100,
child: ListView.builder(
scrollDirection: Axis.vertical,
physics: BouncingScrollPhysics(),
shrinkWrap: true,
itemCount: 5,
itemBuilder: (context, index) {
return Text("Hello World $index");
},
),
);
test this one for second listview
ListView.builder(
physics: NeverScrollableScrollPhysics(),
Just want to add my solution that worked in my case where I have vertical list view together with other buttons and texts on the same screen:
Flexible(
child:
ListView.builder(
// make sure to add the following lines:
shrinkWrap: true,
physics: ScrollPhysics(),
// the rest of your list view code
) // ListView
) // Flexible
This solution works well particularly when you have other widgets on the SAME SCREEN. In this particular case, "Expand" or "Flexible" alone will not work.
There is a widget called Center. It should help you achive what you want to do (center it vertically). Official Documentation for Center widget
Also meet this error, because the code like this
return Container(
child: Column(
children: [
ListView.separated(
itemBuilder: (context, index) {
return CircleManagerSettingItem(widget.membersInfo[index]);
},
separatorBuilder: (_, index) => DD(
height: 1,
paddingLeft: 10,
paddingRight: 10,
),
itemCount: (widget.membersInfo.length)),
],
),
);
remove the Column inside the Container then Ok.
in my case, I had to wrap the ListView inside a Container and give this container a specific Height
I have made a custom function to solve your problem.
You can directly use this function in your code base:
Widget horizontalListView(height, width, color, child, margin) {
return Column(
children: [
SizedBox(
height: 200,
child: ListView.builder(
itemCount: 10,
shrinkWrap: true,
scrollDirection: Axis.horizontal,
itemBuilder: (context,index) {
return Container(
height: height,
width: width,
margin: EdgeInsets.all(margin),
color: color,
child: child
);
}
),
),
],
);
})
P.S. Sorry for bad alignment of code.
You can put Expanded() as a parent of that widget too.
if you are using CustomScrollView
you can try SliverFillRemaining