How to disable Listview Stretching on overscrolling - flutter

I don't know if stretching is the correct word to describe it.
But it looks like this.
"last message 👋👋" is the last message in this convo and the empty space below is the 'stretching'. Once I release the touch from my screen it goes back to normal. I want to disable that 'stretching' so that nothing happens when the user overscrolls.
ListView code:
ListView.builder(
controller: _controller1,
physics: BouncingScrollPhysics(),
itemCount: snapshot.data!.docs.length, //snapshot from parent StreamBuilder
itemBuilder: (context, index) {
final allowedOrNot = index == 0
? true
: compareDate( // Userdefined function to check if the dates above messages should be displayed or not
currentSnap: snapshot.data!.docs[index]
.data()['serverTimeStamp'],
previousSnap: snapshot.data!.docs[index - 1]
.data()['serverTimeStamp']);
return Column(
children: [
allowedOrNot
? chatDater( // the date widget (above some messages to indicate the date of conversation)
data: dataForChatDater( // Userdefined function which returns Strings like 'Yesterday', 'Today' for the widget to display
snap: snapshot.data!.docs[index]
.data()['serverTimeStamp']),
)
: const SizedBox(
width: 0,
height: 0,
),
Align(
alignment:
snapshot.data!.docs[index].data()['sender'] ==
widget.usernameOfFriend
? Alignment.centerLeft
: Alignment.centerRight,
child: MessageBubble( // The ChatBubble widget used to display the messages
timestamp: snapshot.data!.docs[index]
.data()['serverTimeStamp'],
message: snapshot.data!.docs[index].data()['message'],
IsYou: snapshot.data!.docs[index].data()['sender'] ==
widget.usernameOfFriend
? false
: true,
),
),
],
);
},
),

It is natural behavior of BouncingScrollPhysics.
If you don't want to overscroll, you can change it to NeverScrollableScrollPhysics.

Try shrinkWrap:true in your ListView.builder and mainAxisSize:MainAxisSize.min in Column as follows:
ListView.builder(
//other
shrinkWrap: true,
itemBuilder: (context, index) {
return Column(
mainAxisSize: MainAxisSize.min, //use this
children: [
//your children
],
);
})

Related

When adding ListView builder , the entire screen is goes blank

when I try to add a list view builder, my entire screen goes black
here is the list view builder code
ListView.builder(
shrinkWrap = true,
scrollDirection: Axis.horizontal,
itemBuilder: (BuildContext context, int index) {
final data = courseCardList[index];
return Row(
children: [
CourseList(
color: data.color,
icon: data.icon,
caption: data.caption,
head: data.head,
timePeriod: data.timePeriod,
rating: data.rating,
),
],
);
},
),
when I build the UI, that shows a blank screen, what mistake am I making here?
Horizontal Listview.builder needs a fixed height. Horizontal list item shouldn't have a endless height. so solution came to my mind just wrap Listview.builder with a conatiner and set height of that container like below.
The Flutter framework can only know the height of a widget once it's been built.
If you're building ListView children dynamically, it can't calculate the required height of the ListView until all it's children have been built, which might never happen (infinite ListView).
You can either give the ListView a fixed height and build its children dynamically or have the ListView's height depend on it's children.
Container(
height: 200,
child: ListView.builder(
shrinkWrap = true,
scrollDirection: Axis.horizontal,
itemBuilder: (BuildContext context, int index) {
final data = courseCardList[index];
return Row(
children: [
CourseList(
color: data.color,
icon: data.icon,
caption: data.caption,
head: data.head,
timePeriod: data.timePeriod,
rating: data.rating,
),
],
);
},
),
);
Under ListView Widget
use shrinkWrap: true
add itemCount, itemCount: courseCardList.length
If it still doesn't solve the issue,
Remove the Row() widget as I can see you are only returning a single widget under it, so directly return that widget CourseList()
The code should look something like this.
ListView.builder(
shrinkWrap : true,
itemCount: courseCardList.length,
scrollDirection: Axis.horizontal,
itemBuilder: (BuildContext context, int index) {
final data = courseCardList[index];
return CourseList(
color: data.color,
icon: data.icon,
caption: data.caption,
head: data.head,
timePeriod: data.timePeriod,
rating: data.rating,
);
},
),
I think you forgot the itemCount
Expanded(
child:ListView.builder(
shrinkWrap = true,
itemCount = 5,// add this line or put courseCardList.length
scrollDirection: Axis.horizontal,
itemBuilder: (BuildContext context, int index) {
final data = courseCardList[index];
return Row(
children: [
CourseList(
color: data.color,
icon: data.icon,
caption: data.caption,
head: data.head,
timePeriod: data.timePeriod,
rating: data.rating,
),
],
);
},
),
),
Refer ListView and Long List
provide itemCount to your ListviewBuilder and also wrap it with Expanded or some fixed size widget like container like:
Expanded(
child: ListView.builder(
itemCount: your counts(int)
.....
.....
)
)

Flutter: unexpected space at the top of ListView

I have the following source code:
#override
Widget build(BuildContext context) {
return Scaffold(
body: CustomScrollView(
controller: scrollController,
slivers: <Widget>[
SliverList(
delegate: SliverChildBuilderDelegate(
(context, cardIndex) {
return Container(
color: Colors.white,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
'Main Course',
style: kRestaurantMenuTypeStyle,
),
ListView.builder(
itemCount: menuCards[cardIndex].menuItems.length,
shrinkWrap: true,
physics: NeverScrollableScrollPhysics(),
scrollDirection: Axis.vertical,
itemBuilder: (context, itemIndex) {
return RestaurantMenuItem(
menuItem: menuCards[cardIndex].menuItems[itemIndex],
);
},
),
],
),
);
},
childCount: menuCards.length,
),
),
],
),
);
}
Unfortunately, the ListView.builder() creates this extra space on top automatically. This is shown in the image below. That is the big white space between the 'Main Course' and 'Pancit Malabon' texts.
I don't understand why ListView does that. How do I remove the space?
To avoid this behaviour of listview, override padding property with a zero [padding]
return ListView.builder(
padding: EdgeInsets.zero,
itemCount: data.items.length,
itemBuilder: (context, index) {}
);
Looking at your screenshot, the ListView scrolls close to the top of the screen and by default, ListView adds a padding to avoid obstructing the system UI. So a zero padding would remove the extra space.
By default, ListView will automatically pad the list's scrollable
extremities to avoid partial obstructions indicated by MediaQuery's
padding. To avoid this behavior, override with a zero padding
property.
Source : ListView
I solved the issue by adding a padding to my list view like so:
ListView.builder(
padding: EdgeInsets.only(top: 0.0),
...
),
I don't understand why the solution works. If someone can explain the bug, I can accept theirs as the correct answer.
You can wrap your listview with MediaQuery.removePadding
MediaQuery.removePadding(
context: context,
removeTop: true,
child: ListView(...),
)

How to use item count in ListView.Builder?

Click Here for Image! Click here to see error when i input 'itemCount' I want to ask, I am having trouble using the List.builder () feature. where I can't limit the data contained in the list so that it will display an error message about the error range. Here is the source code that I gave.
_sort = <Sort>[
Sort(
category: 'By Games',
item: new Container(
height: 200,
child: new Container(
child: ListView.builder(
scrollDirection: Axis.vertical,
//itemCount: allGames['games'].length,
itemBuilder: (context, index) {
return Container(
child: Padding(
padding: const EdgeInsets.all(15),
child: Text(allGames['games'][index]['game_title'].toString(), style: new TextStyle(color: Colors.white)),
),
);
},
)))),
and here i call the 'Category' and 'Item'. I wrap it in a wrap widget. then for categories, I did divide it into 3 parts. then every part in the category I named 'items' and the problem is the items here have excess capacity so that the data displayed is leftover and not on target.
child: Wrap(
children: <Widget>[
ListView.builder(
shrinkWrap: true,
itemCount: 3,
itemBuilder: (context, index) {
context = context;
if (index < 2) {
final sort = _sort[index];
return ExpansionTile(
title: ListTile(
title: Text(
sort.category,
style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold),
),
),
children: <Widget>[
ListTile(
title: sort.item,
)
],
);
} else {
),
You're accessing allGames["games"] and it says that you're trying to use [] on null.
Seems like allGames is null, so put an eye on that.
Other than that, your use of itemCount is fine!
You can add some null awareness by doing something like this:
itemCount = allGames != null ? (allGames["games"]?.length ?? 0) : 0
I think when the build method runs at the first time, your allGames is null. So, try to add a default value, for example:
itemCount: allGames['games'].length ?? 0

Flutter. Widgets above listview.builder to scroll along with other content?

I'd like to add an info box on top of the listview and instead of having it fixed, I'd like it to scroll along with the content while the page is scrolled down. Instead what I'm experiencing is that it stays always in fixed position no matter what I try to do.
My code:
return new Column(children: <Widget>[
new Text('I want to be scrollable as well with other content as well'), // I want widget or widgets here to be part of the scroll instead of them being fixed.
new Expanded(
child: ListView.builder(
itemBuilder: (BuildContext context, int index) {
return index >= state.posts.length
? BottomLoader()
: PostWidget(post: state.posts[index]);
},
itemCount: state.hasReachedMax
? state.posts.length
: state.posts.length + 1,
controller: _scrollController,
),
),
]);
Is this possible to achieve?
I think you could return your Text widget or any other widget at the 0 position ?
return new Column(children: <Widget>[
new Text('I want to be scrollable as well with other content as well'), // I want widget or widgets here to be part of the scroll instead of them being fixed.
new Expanded(
child: ListView.builder(
itemBuilder: (BuildContext context, int index) {
if (index == 0) {
return Text('Your widget');
else {
return index >= state.posts.length
? BottomLoader()
: PostWidget(post: state.posts[index]);
}
},
itemCount: state.hasReachedMax
? state.posts.length
: state.posts.length + 1,
controller: _scrollController,
),
),
]);

Flutter ListView.Builder() in scrollable Column with other widgets

I have a TabBarView() with an amount of different views. I want of them to be a Column with a TextField at top and a ListView.Builder() below, but both widgets should be in the same scrollable area (scrollview). The way I implemented it threw some errors:
#override
Widget build(BuildContext context) {
return new Column(
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.max,
children: <Widget>[
new Padding(
padding: EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
child: new TextField(
decoration: new InputDecoration(
hintText: "Type in here!"
),
)
),
new ListView.builder(
itemCount: _posts.length, itemBuilder: _postBuilder)
],
);
}
Error:
I/flutter (23520): The following assertion was thrown during performResize():
I/flutter (23520): Vertical viewport was given unbounded height.
I/flutter (23520): Viewports expand in the scrolling direction to fill their container.In this case, a vertical
I/flutter (23520): viewport was given an unlimited amount of vertical space in which to expand. This situation
I/flutter (23520): typically happens when a scrollable widget is nested inside another scrollable widget.
I/flutter (23520): If this widget is always nested in a scrollable widget there is no need to use a viewport because
I/flutter (23520): there will always be enough vertical space for the children. In this case, consider using a Column
I/flutter (23520): instead. Otherwise, consider using the "shrinkWrap" property (or a ShrinkWrappingViewport) to size
I/flutter (23520): the height of the viewport to the sum of the heights of its children.
I read about stacking the ListView.builder() in an Expanded-Area but it made the textfield kind of "sticky" which is not what I want. :-)
I also came across CustomScrollView but didn't fully understand how to implement it.
Here is the solution:
SingleChildScrollView(
physics: ScrollPhysics(),
child: Column(
children: <Widget>[
Text('Hey'),
ListView.builder(
physics: NeverScrollableScrollPhysics(),
shrinkWrap: true,
itemCount:18,
itemBuilder: (context,index){
return Text('Some text');
})
],
),
),
Placing the ListView inside an Expanded widget should solve your problem:
#override
Widget build(BuildContext context) {
return new Column(
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.max,
children: <Widget>[
new Padding(
padding: EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
child: new TextField(
decoration: new InputDecoration(
hintText: "Type in here!"
),
)
),
new Expanded(child: ListView.builder(
itemCount: _posts.length, itemBuilder: _postBuilder))
],
);
}
Use SingleChildScrollView which allows the child widget to scroll
Solution
SingleChildScrollView(
child: Column(
children: <Widget>[
ListView.builder(
shrinkWrap: true,
physics: NeverScrollableScrollPhysics(),
Two properties used here
shrinkWrap: true
only occupies the space it needs (it will still scroll when there more items).
physics: NeverScrollableScrollPhysics()
Scroll physics that does not allow the user to scroll. Means only Column+SingleChildScrollView Scrolling work.
Reason for the error:
Column expands to the maximum size in main axis direction (vertical axis), and so does the ListView
Solution
You need to constrain the height of the ListView, so that it does expand to match Column, there are several ways of solving this issue, I'm listing a few here:
If you want to allow ListView to take up all remaining space inside Column use Flexible.
Column(
children: <Widget>[
Flexible(
child: ListView(...),
)
],
)
If you want to limit your ListView to certain height, you can use SizedBox.
Column(
children: <Widget>[
SizedBox(
height: 200, // constrain height
child: ListView(),
)
],
)
If your ListView is small, you may try shrinkWrap property on it.
Column(
children: <Widget>[
ListView(
shrinkWrap: true, // use it
)
],
)
Use physics: NeverScrollableScrollPhysics() and shrinkWrap: true inside ListView.Builder() and enjoy
Here is an efficient solution:
class NestedListExample extends StatelessWidget {
#override
Widget build(BuildContext context) {
return CustomScrollView(
slivers: [
const SliverToBoxAdapter(
child: Text('Header'),
),
SliverList(
delegate: SliverChildBuilderDelegate(
(ctx, index) {
return ListTile(title:Text('Item $index'));
},
),
),
],
);
}
}
Here is a preview on dartpad.
You can use a SliverToBoxAdapter for the other children as only Slivers can be a direct child of a CustomScrollView.
If all the list items are the same height, then you could use SliverFixedExtentList, which is more efficient because the height of each child isn't calculated on the fly, but you will have to know the exact pixel height. You could also use a SliverPrototypeExtentList, where you provide the first item in the list(the prototype), and all the other children will use the height of the prototype so you don't need to know the exact height in pixels.
Use Expanded widget to constrain without overflowing those pixels, :)
Column(
children: <Widget>[
Expanded(
child: ListView(),
),
Expanded(
child: ListView(),
),
],
)
just add
Column(
mainAxisSize: MainAxisSize.max, //Add this line onyour column
children:[
SomeWidget(),
Expanded(child:ListView.builder())
]
)
In my case with a future i did it like this:
SingleChildScrollView(
physics: ScrollPhysics(),
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Text("Hey ho let's go!"),
Flexible(
child: FutureBuilder(
future: getData(),
builder: (BuildContext context,
AsyncSnapshot<List<Sale>> snapshot) {
if (snapshot.connectionState != ConnectionState.done ||
snapshot.hasData == null) {
return CircularProgressIndicator();
} else {
data = snapshot.data;
return ListView.builder(
physics: NeverScrollableScrollPhysics(),
shrinkWrap: true,
itemBuilder: (BuildContext context, int index) {
return dataItemWidget(size, data[index], context);
},
itemCount: data.length,
);
}
},
),
),
],
),
),
//If you want Listview.builder inside ListView and want to scroll the parent ListView// //whenever the Items in ListView.builder ends or start you can do it like this
body: ListView(
physics: ScrollPhysics(),
children: [
SizedBox(height: 20),
Container( height: 110.0 *5, // *5 to give size to the container //according to items in the ListView.builder. Otherwise will give hasSize Error
child:ListView.builder(
physics: NeverScrollableScrollPhysics(),
scrollDirection: Axis.vertical,
itemCount: 5,
itemBuilder: (BuildContext context, int indexChild) {
return InkWell(child:Container(height:100));}))
),]),
The best way will be to make the column scrollable by making the column child of SingleChildScrollView and then assigning the same ScrollController to both the SingleChildScrollView and the ListView.builder. This will make the text field and the below ListView as scrollable.
Just add physics: NeverScrollableScrollPhysics() in ListView.builder() so you can scroll
Add physics: NeverScrollableScrollPhysics() inside Listview.builder() method and the nested Listview will scroll
Column is not scrollable, which is why the TextField on top wouldn't scroll but the ListView on the bottom would.
The best way to solve this in my opinion is to make your TextField the first item in your ListView.
So you won't need a column, your parent widget is the ListView, and its children are the TextField followed by the remaining items you build with _postBuilder.
return Column(
children: [
Text("Popular Category"),
Expanded(
child: ListView.builder(`enter code here`
shrinkWrap: false,
scrollDirection: Axis.horizontal,
itemCount: 3,
itemBuilder: (context, index) {
return Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text("hello"),
],
);
}),
),
],
);
body: SingleChildScrollView(
physics: ScrollPhysics(),
child: Column(
children: [
getFiltersOnHomePage(),
SizedBox(
child: StreamBuilder(
stream: FirebaseFirestore.instance.collection('posts').snapshots(),
builder: (context,
AsyncSnapshot<QuerySnapshot<Map<String, dynamic>>> snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return const Center(
child: CircularProgressIndicator(),
);
}
return ListView.builder(
physics: NeverScrollableScrollPhysics(),
shrinkWrap: true,
itemCount: snapshot.data!.docs.length,
itemBuilder: (ctx, index) => Container(
margin: EdgeInsets.symmetric(
horizontal: width > webScreenSize ? width * 0.3 : 0,
vertical: width > webScreenSize ? 15 : 0,
),
child: PostCard(
snap: snapshot.data!.docs[index].data(),
),
));
},
),
),
],
),
),[enter image description here][1]***You will be able to scroll through the page by using Expanded Widget
Blockquote
Using this you can scroll over the entire page. This page includes a row and a listview builder inside a scrollable column.
In my case, I added a Container with transparent color and height up to 270 to solve this one.
Column(
children: <Widget>[
ListView(
shrinkWrap: true, // use it
),
Container(
color: Colors.transparent,
height: 270.0,
),
],
)