This article shows you how to safely nest a ListView or a GridView inside a Column.
Problem
When building Flutter applications, you may run into the following error:
Vertical viewport was given unbounded height
The error commonly happens when you wrap a ListView or a GridView by a Column. All of these widgets are scrollable and expand to the maximum size in the main axis direction by default. Nesting a scrollable widget inside another scrollable widget gives the viewport an unlimited amount of vertical space in which to expand.
Solutions
There are several approaches to solving the mentioned problem.
Adding an Expanded widget
The Expanded widget makes the ListView fill the available space along the main axis of the Column.
Example:
class HomePage extends StatelessWidget {
HomePage({Key? key}) : super(key: key);
final List _items = List.generate(10000, (index) {
return "Item $index";
});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Kindacode.com'),
),
body: Column(
children: [
Expanded(
child: ListView.builder(
itemCount: _items.length,
itemBuilder: (_, index) => ListTile(
title: Text(
_items[index],
)),
),
)
],
));
}
}
Adding a constraint
Wrapping the ListView or GridView widget with a Container or a SizedBox can solve the problem.
Example:
Column(
children: [
SizedBox(
height: 600,
child: ListView(),
),
)
],
)
Adding a Flexible widget
The Flexible widget can control how a child of a Column flexes. Like the Expanded widget, Flexible gives ListView the flexibility to fill the available space in the main axis.
Example:
Column(
children: [
Flexible(
child: ListView.builder(
itemCount: //...
itemBuilder: //..
),
)
],
)
Conclusion
This article walked through a few ways to solve a typical error that happens when a ListView or a GridView is nested inside a Column. If you would like to explore more things about Flutter, take a look at the following articles:
- Working with Table in Flutter
- /Flutter: Global, Unique, Value, Object, and PageStorage Keys
- How to Create a Stopwatch in Flutter
- 2 Ways to Create Typewriter Effects in Flutter
- Flutter ConstrainedBox
- Using Stack and IndexedStack in Flutter
You can also check out our Flutter topic page or Dart topic page for the latest tutorials and examples.