skip to Main Content

I have a ListView.builder that uses shrinkWrap because I get an error if I don’t use it.

As a result of this answer, there will be a lot of white space above ListView.builder:

The result of the answer

How can I remove it?

My code:

SingleChildScrollView(
  child: Column(
    crossAxisAlignment: CrossAxisAlignment.start,
    children: [
      Text(
        "Summary",
        maxLines: 1,
        overflow: TextOverflow.ellipsis,
      ),
      const SizedBox(height: 20.0),
      Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          …
        ],
      ),
      ListView.builder(
        shrinkWrap: true,
        cacheExtent: 9999,
        itemCount: list.length,
        itemBuilder: (context, index) => ListTile(…),
      ),
    ],
  ),
),

Feel free to leave a comment if you need more information.

How can I change the position of the ListView.builder that uses shrinkWrap?

2

Answers


  1. Chosen as BEST ANSWER

    Instead of using ListView.builder, you should use Column:

    Column(
      children: list.map((element) => …).toList(),
    ),
    

  2. I don’t know by "space above ListView.builder" or "How can I change the position of the ListView.builder that uses shrinkWrap?" what you mean

    Possible solutions considering all cases:

    • If it’s outside the ListView is because of wrapping it in Center which is obvious.

    • If you are referring to the top margin inside the ListView it is because of this line margin: EdgeInsets.all(32),

    • You just have to remove Center widget, it will change it’s position to the start of the app.

    Extra: You can remove the default padding of ListView.builder by adding padding:EdgeInsets.zero. If this is what you are talking about.

    Scaffold(
              body: Container(
            decoration: BoxDecoration(
                border: Border.all(color: Colors.red), color: Colors.amber),
            child: ListView(
              padding: EdgeInsets.zero,
              shrinkWrap: true,
              children: const <Widget>[
                ListTile(title: Text('Item 1')),
                ListTile(title: Text('Item 2')),
                ListTile(title: Text('Item 3')),
              ],
            ),
          )),
    
    
    

    enter image description here

    Note: You dont have to use shrinkWrap:true everytime , it is preferred to be used, only when your listView is inside another Scrollable view. Else it is preferred to be false which is the option by default


    Refer the docs:

    Shrink wrapping the content of the scroll view is significantly more expensive than expanding to the maximum allowed size because the content can expand and contract during scrolling, which means the size of the scroll view needs to be recomputed whenever the scroll position changes.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search