What is the difference between ListView and ListView.builder and can we use Listview.builder to create and validate and submit forms? - flutter

What is the difference between Listview.builder and Listview?
Can we use ListView.builder to submit forms?
I am using the Listview.builder now to create forms.

From official docs:
https://api.flutter.dev/flutter/widgets/ListView/ListView.html
ListView: Creates a scrollable, linear array of widgets from an
explicit List.
This constructor is appropriate for list views with a small number of
children because constructing the List requires doing work for every
child that could possibly be displayed in the list view instead of
just those children that are actually visible.
https://api.flutter.dev/flutter/widgets/ListView/ListView.builder.html
ListView.builder Creates a scrollable, linear array of widgets that
are created on demand. This constructor is appropriate for list views
with a large (or infinite) number of children because the builder is
called only for those children that are actually visible.
Basically, builder constructor create a lazy list. When user is scrolling down the list, Flutter builds widgets "on demand".
Default ListView constructor build the whole list at once.
In your case, default construct works fine, because you already now how many widgets should put on Column().

The main difference between ListView and ListView.builder
The ListView constructor requires us to create all items at once. This is good when list items are less and all will be seen on the screen, but if not then for long list items its not the good practice.
whereas
the ListView.Builder constructor will create items as they are scrolled onto the screen like on-demand. This is the best practice for development for List widget where items will only render only when items are going seen on the screen.

ListView.builder() builds widgets as required(when they can be seen). This process is also called "lazily rendering widgets".

To see the difference between each one go visit ListView Class.
And sure, you can create Forms with ListView.builder(), but I've found some problems trying it.
I can't put it into any ListView(), either Column(), to put them if there's any more items than just the Form().
I couldn't even add a Button at the of the ListView.builder() even using a conditional to put it when the last index is reached. Because of that, you have to use textInputAction: TextInputAction.done to perform some kind of action at onFieldSubmitted:
The best way to get the Fields data I've found was to add them all into an array when the onSaved:method is called, and I don't think that's a good way to go (maybe it is).
With that being said, that's what I used to make it work:
body: Form(
key: _key,
child: Container(
child: ListView.builder(
itemCount: 5,
itemBuilder: (context, index) {
return TextFormField(
textInputAction: TextInputAction.done,
validator: (text) {
if (text.isEmpty) {
return "The text is empty";
}
},
onFieldSubmitted: (text) {
_onSaved();
},
onSaved: (text) {
form.add(text);
},
);
},
),
),
),
void _onSaved() {
if (_key.currentState.validate()) {
_key.currentState.save();
print(form);
}
}
And the result:
I/flutter ( 7106): [fjjxjx, hxjxjcj, jxjxjfj, jfjfj, jxjxj]

This answer for those who are coming from native android background.
ListView is like listview in android
ListView.builder is recyclerView in android
In case you don't know recyclerView only render those view which are visible in screen and reuse them again and again to save resources.
RecyclerView when there is alot of data.

Related

Getting scroll index from scrolling position in pixels listview flutter

Is there a way we can use ScrollController.position.pixels to know the scrolling index of a listview in flutter? I'm trying to restore the last scrolling index between app restarts.
You can use the flutter_scrollview_observer lib to implement your desired functionality without invasivity
Create and use instance of ListView normally.
ListView _buildListView() {
return ListView.separated(
...
);
}
Pass the ListView instance to the ListViewObserver, then you can obtain the desired result in the onObserve callback
ListViewObserver(
child: _buildListView(),
onObserve: (resultModel) {
print('firstChild.index -- ${resultModel.firstChild?.index}');
print('displaying -- ${resultModel.displayingChildIndexList}');
},
)

Using TextField and Button to create a message bubble in Flutter

Android Studio + Flutter
I have a Row at the bottom of the screen.
It includes TextField and Button (Add).
When there is some text in TextField and user clicks Add, I want it to appear as a Bubble inside a Container starting from the top left.
What would be the correct way to do it? I want the bubbles to accumulate like a notes app and eventually be scrollable too.
Thanks!
Try using the Snackbar Widget, which can be personalized heavily.
Here's the documentation.
EDIT. Since you want a permanent list of bubbles on the top, I'd suggest using a provider, so that when you click the button, the onTap event validates and adds the data to a list (below, myElements). Then, up to the top, just add a Consumer Widget that listens to changes to the list (it rebuilds its children every time something changes). In the following example code (I have not tested it!) I use an Expanded widget just for fun and I use a ListView.builder inside the Consumer to show the list of elements you've added, since the amount of added element could be high. Finally, I suggest using either ListTile or Card or a combination of the two, since you want something aesthetically beatiful like a bubble (you'll have to play with the settings, a little):
return ... (
child: Column(
children: [
Text("Some title..?"),
Expanded(
Consumer(
builder: (ctx, myElements, _) => ListView.builder(
itemCount: myElements.length,
itemBuilder: (ctx, i) => ListTile(
title: Text("You added ${myElements[i]}"),
// something else...?
),
),
),
),
Row( /* ... Text field + Button here... */),
],
),
// ...

ListView.builder's index doesn't reset when calling setState. Found a weird fix for it. Is there a better solution? Why is this happening?

I have this listview.builder which is supposed to show some orders from an array of Order objects based on their status.
It looks kinda like this:
The List works just fine until, for some reason, when I scroll down and the viewport can only display the order with index (the one in the listview builder function) 5 and then press another category like "New", setState() is called and the whole thing rebuilds, but the builder's index starts at 5 and the listview.builder doesn't build anything from 0 - 4. I've printed the index in the builder and caught this bug, but I still don't understand why this is happening.
This is what my listview.builder code looks like:
ListView.builder(
controller: _scrollController,
shrinkWrap: true,
itemBuilder: (BuildContext context, int index) {
print("INDEX: $index");
return _showOrder(index);
},
itemCount: orders.length,
),
This is the code for _showOrder():
Widget _showOrder(int i) {
String _currOrderStatus = orders[i].orderStatus;
/// _selectedOrderStatus is just a String which changes depending on the selected category of orders.
/// e.g. "New" or "Past"
return _currOrderStatus == _selectedOrderStatus
? ShowMyOrderWidget()
: SizedBox(
/// AND FOR SOME REALLY WEIRD REASON, THIS FIXES THE PROBLEM
/// It works with any height, as long as it's not 0, but if I have a lot of them, then the
/// layout gets spaced out and messy. With such a low number, this is highly unlikely, but
/// still seems like a stupid fix.
/// Why does this work? Why is this happening? Is there a better way to fix it?
height: 0.000000001,
);
}
And I just call setState() in the onPressed() function of those buttons on top of the screen.
Changing the items inside the ListView doesn't reset scroll position.
Since you're already assigning a ScrollController to your ListView, try calling "jumpTo(0.0)" to reset it's scroll position before calling setState().
_scrollController.jumpTo(0.0);

How to dynamically add Children to Scaffold Widget

Let's say, I have a chat screen that looks like this.
Now, when the user clicks the "Press when ready" button, the method fetchNewQuestion() is called.
My intention is that this will make a HTTP request, and display the result using
_buildUsersReply(httpResponse);
But, the problem is that this return must be made inside the current scaffold's widget as a child under the existing children, so that it is built at the bottom with the previous ones still there. The result would be like this:
You can find my complete code here.
Is this possible to be done pro-grammatically? Or do I have to change the concept of how I do this?
[Update, I now understand that my approach above is wrong and I have to use a listview builder. CurrentStatus below shows my progress towards achieving that goal.]
Current status:
I have built a list of Widgets:
List<Widget> chatScreenWidgets = [];
And on setState, I am updating that with a new Widget using this:
setState(() { chatScreenWidgets.add(_buildUsersReply("I think there were 35 humans and one horse.")); });
Now at this point, I am not sure how to pass the widget inside the scaffold. I have written some code that does not work. For instance, I tried this:
Code in the image below and in the gist here:
Just for future reference, here is what I really needed to do:
1. Create a list of widgets
List<Widget> chatScreenWidgets = [];
2. Inside my method, I needed to use a setState in order to add elements to that list. Every widget I add to this will be displayed on ths Scaffold.
`setState(() {
chatScreenWidgets.add(_buildUsersReply("Some Text"));
});`
3. And then, load that inside my Scaffold, I used an itemBuilder in order to return a list of widgets to my ListView. I already had that ListView (where I was manually adding children). Now this just returns them through the setState method inside my business logic method (in this case, fetchNewQuestion()).
body: Stack(
children: <Widget>[
Padding(
padding: EdgeInsets.only(bottom: 0),
child: new ListView.builder(
physics: BouncingScrollPhysics(),
padding: EdgeInsets.symmetric(horizontal: 25),
itemCount: chatScreenWidgets.length,
itemBuilder: (BuildContext context, int itemCount) {
return chatScreenWidgets[itemCount];
}
),
),
],
),
);`
I hope this helps future flutter engineers!
forget about the scaffold the idea is about what you really want to change, lets say it is
a list and your getting the data from an array if you update the array, then the list will update,if it is another type widgets then you can handle it in a different way i will edit this answer if you clarify what each part does in your widget as i cant read your full code.
first you have to create an object with two attributes one is the type of the row(if it is a user replay or other messages) and the second attribute is the string or the text.
now create a global list in the listview class from the above object, so you get the data from the user or even as a news and you create a new object from the above class and add your data to it and add it to the list.
item builder returns a widget so according to the the widget that you return the row will be set , so according to the data in the object call one of your functions that return the views like _buildUsersReply(string text).
if you have any other question you can ask :) if this what you need please mark it as the answer.

Flutter : Textfield in ListView.builder

Hi everyone i have some data at Cloud Firestore and a ListView.builder to load the data in it. In this ListView.builder i have Network.Image, ListTile to show the title and subtitle and another ListTile which has a Textfield to add some comment and an iconbutton. My goal is to get the text of the textfield and show as a alertDialog when the button clicked. Until now i added a controller to the textfield but whenever i type anything in the textfield it changes all the textfields. I have tried creating a List to specify a unique controller so i can stop the all of the changes in textfields but i have failed. Is there any way i can do this. All this textfields and iconbuttons must be unique so when i clicked the iconbutton i need to see the text of the typed textfield.
Try using
List<TextEditingController> _controllers = new List();
//try below in null-safe
//List<TextEditingController>? _controllers = [];
And inside your ListView.builder add a new controller for each item.
ListView.builder(
itemBuilder: (context,index){
_controllers.add(new TextEditingController());
//try below in null-safe
//_controllers!.add(TextEditingController());
//Your code here
}),
To access the controller's text you will need the index value
_controllers[index].text
Make sure to dispose of all textControllers in the end.
You might want to consider making a new type of custom Widget for each row.
You can leverage a
TextEditingController (where you call the corresponding controller
on click or the
TextField's onChanged callback (where you store the new value for
the corresponding item on change
In both cases you have a somewhat nasty list of either text controllers or String values.
Remember, ListView.builder is only going to build the items that are in or near the viewport (as you scroll).
the builder is called only for those children that are actually visible
That means that you can have the same row built multiple times (
Consider using a custom widget for each row (extend StatefulWidget)
This will alleviate the coordination involved with all the roles and it will push any resulting state further down the tree to the leaf nodes
If using a TextEditingController:
you only have one controller to worry
call _textController.dispose() in the widget's dispose() method
If using a onChanged callback (available on TextField not TextFormField)
create a String variable as state in the custom widget inputValue
handle the null cases
read from this when the button is tapped
It looks like the TextEditingController may be easiest, but I wanted to mention both options for your consideration.
ListView.builder(
shrinkWrap: true,
physics: ScrollPhysics(),
itemCount: list.length,
itemBuilder: (BuildContext context, int index) {
_controllers.add(new TextEditingController());
return Container(
child: TextField(
textAlign: TextAlign.start,
controller: _controllers[index],
autofocus: false,
keyboardType: TextInputType.text,),))