What is the difference between ListView and SingleChildScrollView+ListBody in Flutter?

Viewed 46

I have a question about comparing ListView and SingleChildScrollView containing a ListBody. Seemingly, those two results look the same. But I'm curious about whether those two have a difference in function. In my opinion, it could be the part of efficiency or performance, but I'm not sure. Thanks in advance.

SingleChildScrollView + ListBody

final items = List.generate(100, (index) => index).toList();

SingleChildScrollView(
  child: ListBody(
    children: items.map((e) => Text('$e')).toList(),
  )
)

ListView

final items = List.generate(100, (index) => index).toList();

ListView(
  children: items.map((e) => Text('$e')).toList(),
)
2 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.

I must say I actually have never even heard of the widget ListBody, but when you check its source code you can actually see the comment:

/// This widget is rarely used directly. Instead, consider using [ListView],
/// which combines a similar layout algorithm with scrolling behavior, or
/// [Column], which gives you more flexible control over the layout of a
/// vertical set of boxes.

So the flutter devs themselves sort of don't recommend using it. I also don't know what the exact difference is, so I guess I'm not really answering your question. Maybe someone else can, but you also could just investigate the source code yourself, since it's all open source.

Related