What does the shrinkWrap property do in Flutter?

I am new to Flutter and very eager to learn this technology. I cannot understand the work of shrinkWrap property in ListView. I couldn't understand the Flutter documentation.


Solution 1:

Usually a ListView (as well as GridView, PageView and CustomScrollView) tries to fill all the available space given by the parent element, even when the list items would require less space.

With shrinkWrap: true, you can change this behavior so that the ListView only occupies the space it needs (it will still scroll when there more items).

Take a look at this example:

import 'package:flutter/material.dart';

void main() => runApp(App());

class App extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(),
        body: Center(
          child: Container(
            margin: EdgeInsets.all(32),
            decoration: BoxDecoration(border: Border.all(color: Colors.red)),
            child: ListView(
              shrinkWrap: false,
              children: <Widget>[
                ListTile(title: Text('Item 1')),
                ListTile(title: Text('Item 2')),
                ListTile(title: Text('Item 3')),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

With shrinkWrap: false:

without shrinkWrap

With shrinkWrap: true:

with shrinkWrap

You can use this in AlertDialogs: When there are only a few items, make the dialog as small as possible. When there are many items, fill the screen height and make the list scrollable:

Dialog

Dialog

Solution 2:

If you do not set the shrinkWrap property, your ListView will be as big as its parent.

If you set it to true, the list will wrap its content and be as big as it children allows it to be.

Solution 3:

Every ScrollView (ListView , GridView , CustomScrollView) have a shrinkWrap property for determining the size of scrollDirection.

So ScrollView's scrollDirection can have 02 sizes.

  1. Same size as parent size.
  2. Same size as content size (All children size).

If ScrollView's shrinkWrap : false , Then ScrollView's scrollDirection size is same size as parent size.

If the ScrollView's shrinkWrap : true , Then ScrollView's scrollDirection size is same size as Content size (All children size).

But Why ScrollView scrollDirection is need to switch between these 02 sizes ???

Reason is ScrollView's parent constraints.

  • If ScrollView's parent give an Tight or Loose constraint , Then your ScrollView's scrollDirection size is same as its parent size. [shrinkWrap : false].
  • If ScrollView's parent give an Unbound constraint , Then your ScrollView's scrollDirection size must need to be same as its Content size. [shrinkWrap : true]. Otherwise it will give an unbound height runtime exception