Based on your app requirement, you may want to add the ListView inside the Column or Row. But if you do so, you may get an error called ‘RenderBox was not laid out’. So in this tutorial, we’ll explain why did you get the error called RenderBox was not laid out in Flutter and how to fix it.
Here’s what we’ll cover:
- How’s the Error Looks Like?
- Why Did you Get this Error?
- Ways to Fix RenderBox was not Laid Out
How’s the Error Looks Like?
Here’s how the error looks like when you try to add the scrollable widget such as ListView, GiridView inside another scrollable widget such as Column or Row.
Why Did you Get this Error?
The reason for getting this error is that you have added one scrollable widget DIRECTLY inside another scrollable widget. i.e A ListView, GridView directly inside the Column or Row.
The ListView, GridView takes all the available space in a vertical/horizontal direction and the Column/Row widget doesn’t add any constraint on its children’s height/width. This makes it difficult for the Flutter to calculate the size of ListView/GridView.
Ways to Fix RenderBox was not Laid Out
To fix the RenderBox was not laid out error, There are mainly three ways you can try:
- Using SizedBox
- Using ShrinkWrap
- Using Expanded (Recommended)
1. Using SizedBox
- Wrap your ListView widget inside the SizedBox widget.
- Add the height parameter to the SizedBox and give it a fixed height.
Column( children: [ SizedBox( height: 400, child: ListView( children: const <Widget>[...], ), ), ], )
Note: This makes the ListView appear in a limited portion instead of infinite size.
2. Using shrinkWrap
If you don’t like putting your ListView inside the limited portion, you can also add the shrinkWrap parameter to the ListView and make it True.
Column( children: [ ListView( shrinkWrap: true, // <---- Here children: const <Widget>[...], ), ], )
Note: ListView widget shrinks down to its children’s size.
3. Using Expanded (Recommended)
The simplest and recommended approach is to wrap your ListView inside the Expanded widget. This will make the ListView grow as long as Column or Row allows.
Column( children: [ Expanded( child: ListView( children: const <Widget>[...], ), ), ], )
That’s it Thanks.
In this tutorial, we learned that to fix the RenderBox was not laid out in error by using the SizedBox or Expanded widget. If you’d don’t want to wrap your ListView inside another widget you can simply set the shrinkWrap property to true.
Would you like to check other interesting Flutter tutorials?