Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between ListView and SingleChildScrollView in Flutter?

I have seen few examples using ListView as the main body element of Scaffold and in few tutorials, it's SingleChildScrollView. All that I understood is both allow some axis of scrolling based on the direction that is configured but cannot figure out when to use one over the other?

ListView:

Scaffold
  body : ListView
    children : Padding/Container

SingleChildScrollView:

Scaffold
  body : SingleChildScrollView
    child : Column
like image 608
BeingSuman Avatar asked Jun 02 '20 06:06

BeingSuman


Video Answer


3 Answers

You could consider ListView as an optimisation to the combination of SingleChildScrollView + Column.

By using ListView, only the items that are visible are mounted and painted.

On the other hand, by using SingleChildScrollView+Column, the entire item list is mounted+painted, even if only a few items are visible.

The tradeoff is that ListView is less flexible. So for complex layouts with a small number of items, the performance gain may not be worth the trouble, in which case we can use SingleChildScrollView.

like image 122
Rémi Rousselet Avatar answered Oct 16 '22 13:10

Rémi Rousselet


ListView: is used when we have to render the same kind of widgets for n elements

SingleChildScrollView: is used when we have different widgets for n elements.

Ideally, both the cases we required scrolling, Listview have default behavior, but column and other widgets don't have so required to use SingleChildScrollView

Updated: One important point you should take care while choosing ListView

 ListView() -- Render all the items in the list, even if it is not visible. 

`ListView.Builder()` -- Render only visible items on the screen. 
like image 23
Jitesh Mohite Avatar answered Oct 16 '22 14:10

Jitesh Mohite


ListView, you would use, if you have a list of UI widgets to render, and the number of such widgets is dynamic.

For example: You need to only show a list of contacts on your screen and the list items are more or less similar (UI wise and category wise). Then you would use a Listview.

A SingleChildScrollView can be compared to "ScrollView" in Android. Suppose you have a lot of UI widgets (Buttons, InputFields, Cards, etc), and they start going out of the screen. In such cases, your widgets will overflow and you will start seeing warnings. To fix this, you wrap your UI widgets with a SingleChildScrollView.

For your usecase, "Recommended" section, ListView would be a good choice.

like image 37
Kumar Bibek Avatar answered Oct 16 '22 13:10

Kumar Bibek