use of shrinkWrap in listview Flutter
In Flutter, the “shrinkWrap” property in a ListView widget controls whether the ListView should adjust its size based on the size of its contents. It is used to determine whether the ListView should take up as much space as it can (when set to false
) or only as much space as required by its children (when set to true
).
Here’s a more detailed explanation of the role of the “shrinkWrap” property in a ListView:
- shrinkWrap: false (default):
- When “shrinkWrap” is set to
false
, the ListView will expand to fill all the available vertical space, regardless of the size of its children. - This is typically used when you have a ListView inside a scrollable parent, such as a SingleChildScrollView or another ListView. In such cases, the inner ListView can scroll independently, and the outer scrollable widget (e.g., SingleChildScrollView) will control the overall scrolling behavior.
import 'package:flutter/material.dart';
class ShrinkWrapExample 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')),
],
),
),
),
),
);
}
}
it contains all available space
shrinkwrap: True
But if we pass false to shrinkwrap: true
It will contain only the space it needs
import 'package:flutter/material.dart';
class ShrinkWrapExample 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: true,
children: <Widget>[
ListTile(title: Text('Item 1')),
ListTile(title: Text('Item 2')),
ListTile(title: Text('Item 3')),
],
),
),
),
),
);
}
}