Flutter: Safety nesting ListView, GridView inside a Column

Last updated on January 26, 2021 A Goodman Loading... Post a comment

This article shows you how to safety 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 solve the mentioned problem.

1 – 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 {
  final List _items = List.generate(10000, (index) {
    return "Item $index";
  });

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('Kindacode.com'),
        ),
        body: Column(
          children: [
            Expanded(
              child: ListView.builder(
                itemCount: _items.length,
                itemBuilder: (_, index) => ListTile(
              title: Text(_items[index],)
                ),
              ),
            )
          ],
        ));
  }
}

2 – 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(),
              ),
            )
         ],
)

3 – Adding a Flexible widget

The Flexible widget can control how a child of a Column flexes. Like the Expanded widget, Flexible gives the 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: Write a simple BMI Calculator with FlutterWorking with Table in FlutterFlutter ConstrainedBoxUsing Stack and IndexedStack in Flutter.

You can also check out our Flutter topic page or Dart topic page for the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles