ListView Class in Flutter (original) (raw)
In Flutter, ListView is a scrollable list of widgets arranged linearly. It displays its children sequentially in the scrolling direction, either vertically or horizontally.
There are different types of ListViews :
- **ListView
- **ListView.builder
- **ListView.separated
- **ListView.custom
**Constructor of ListView Class:
ListView ListView({
Key? key,
Axis scrollDirection = Axis.vertical,
bool reverse = false,
ScrollController? controller,
bool? primary,
ScrollPhysics? physics,
bool shrinkWrap = false,
EdgeInsetsGeometry? padding,
double? itemExtent,
double? Function(int, SliverLayoutDimensions)? itemExtentBuilder,
Widget? prototypeItem,
bool addAutomaticKeepAlives = true,
bool addRepaintBoundaries = true,
bool addSemanticIndexes = true,
double? cacheExtent,
List children = const [],
int? semanticChildCount,
DragStartBehavior dragStartBehavior = DragStartBehavior.start,
ScrollViewKeyboardDismissBehavior keyboardDismissBehavior = ScrollViewKeyboardDismissBehavior.manual,
String? restorationId,
Clip clipBehavior = Clip.hardEdge,
HitTestBehavior hitTestBehavior = HitTestBehavior.opaque,
})
**Constructor of ListView.builder Class:
ListView ListView.builder({
Key? key,
Axis scrollDirection = Axis.vertical,
bool reverse = false,
ScrollController? controller,
bool? primary,
ScrollPhysics? physics,
bool shrinkWrap = false,
EdgeInsetsGeometry? padding,
double? itemExtent,
double? Function(int, SliverLayoutDimensions)? itemExtentBuilder,
Widget? prototypeItem,
required Widget? Function(BuildContext, int) itemBuilder,
int? Function(Key)? findChildIndexCallback,
int? itemCount,
bool addAutomaticKeepAlives = true,
bool addRepaintBoundaries = true,
bool addSemanticIndexes = true,
double? cacheExtent,
int? semanticChildCount,
DragStartBehavior dragStartBehavior = DragStartBehavior.start,
ScrollViewKeyboardDismissBehavior keyboardDismissBehavior = ScrollViewKeyboardDismissBehavior.manual,
String? restorationId,
Clip clipBehavior = Clip.hardEdge,
HitTestBehavior hitTestBehavior = HitTestBehavior.opaque,
})
**Constructor of ListView.separated Class:
ListView ListView.separated({
Key? key,
Axis scrollDirection = Axis.vertical,
bool reverse = false,
ScrollController? controller,
bool? primary,
ScrollPhysics? physics,
bool shrinkWrap = false,
EdgeInsetsGeometry? padding,
required Widget? Function(BuildContext, int) itemBuilder,
int? Function(Key)? findChildIndexCallback,
required Widget Function(BuildContext, int) separatorBuilder,
required int itemCount,
bool addAutomaticKeepAlives = true,
bool addRepaintBoundaries = true,
bool addSemanticIndexes = true,
double? cacheExtent,
DragStartBehavior dragStartBehavior = DragStartBehavior.start,
ScrollViewKeyboardDismissBehavior keyboardDismissBehavior = ScrollViewKeyboardDismissBehavior.manual,
String? restorationId,
Clip clipBehavior = Clip.hardEdge,
HitTestBehavior hitTestBehavior = HitTestBehavior.opaque,
})
**Constructor of ListView.custom Class:
ListView ListView.custom({
Key? key,
Axis scrollDirection = Axis.vertical,
bool reverse = false,
ScrollController? controller,
bool? primary,
ScrollPhysics? physics,
bool shrinkWrap = false,
EdgeInsetsGeometry? padding,
double? itemExtent,
Widget? prototypeItem,
double? Function(int, SliverLayoutDimensions)? itemExtentBuilder,
required SliverChildDelegate childrenDelegate,
double? cacheExtent,
int? semanticChildCount,
DragStartBehavior dragStartBehavior = DragStartBehavior.start,
ScrollViewKeyboardDismissBehavior keyboardDismissBehavior = ScrollViewKeyboardDismissBehavior.manual,
String? restorationId,
Clip clipBehavior = Clip.hardEdge,
HitTestBehavior hitTestBehavior = HitTestBehavior.opaque,
})
Demo Code
Implement the static code in **main.dart and **use the below ListView codes in the body of the scaffold to gain a better understanding of ListView.
**main.dart:
Dart `
import 'package:flutter/material.dart';
void main() { runApp(MyApp()); }
class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'FAB', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(), debugShowCheckedModeBanner: false, ); } }
class MyHomePage extends StatefulWidget { @override _MyHomePageState createState() => _MyHomePageState(); }
class _MyHomePageState extends State {
@override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text( "ListView", ), backgroundColor: Colors.green, foregroundColor: Colors.white, ), body: // use the below ListView codes here to gain a better understanding of ListView. ); } }
`
**ListView()
This is the default constructor of the **ListView class. A ListView simply takes a list of widgets and makes it scrollable. Usually, this is used with a few children as the List will also construct invisible elements in the list, so numerous widgets may render this inefficiently.
**Properties of Listview:
Property | Description |
---|---|
**clipBehaviour | This property Creates a scrollable, linear array of widgets from an explicit List. |
**itemExtent | The itemExtent takes in a double value as the object to controls the scrollable area in the ListView. |
**padding | It holds EdgeInsetsGeometryI as the object to give space between the Listview and its children. |
**scrollDirection | This property takes in _Axis enum as the object to decide the direction of the scroll on the _ListView. |
**shrinkWrap | This property takes in a boolean value as the object to decide whether the size of the scrollable area will be determined by the contents inside the _ListView. |
**Code for ListView :
Dart `
ListView( padding: EdgeInsets.all(20), children: [ CircleAvatar( maxRadius: 50, backgroundColor: Colors.black, child: Icon(Icons.person, color: Colors.white, size: 50), ), Center( child: Text( 'Sooraj S Nair', style: TextStyle( fontSize: 50, ), ), ), Text( """Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a gallery of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum,It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).""", style: TextStyle( fontSize: 20, ), ), ], ),
`
**Output:
**ListView.builder()
The builder() constructor constructs a repeating list of widgets. The constructor takes two main parameters:
**Properties of Listview.builder():
Property | Description |
---|---|
**itemCount | It is for the number of repetitions for the widget to be constructed (not compulsory). |
**itemBuilder | It is for constructing the widget which will be generated '**itemCount' times (compulsory). |
**Note: If the itemCountis not specified, **infinite widgets will be constructed by default.
**Code for ListView.builder() :
Dart `
ListView.builder( itemCount: 20, itemBuilder: (context, position) { return Card( child: Padding( padding: const EdgeInsets.all(20.0), child: Text( position.toString(), style: TextStyle(fontSize: 22.0), ), ), ); }, ),
`
**Output:
ListView.separated ()
The ListView.separated() constructor is used to generate a list of widgets, but in addition, a **separator widget can also be generated to separate the widgets. In short, these are two intertwined list of widgets: the main list and the separator list. Unlike the builder() constructor, the **itemCountparameter is compulsory here.
**Code for ListView.separated():
Dart `
ListView.separated( itemBuilder: (context, position) { return Card( child: Padding( padding: const EdgeInsets.all(15.0), child: Text( 'List Item $position', ), ), ); }, separatorBuilder: (context, position) { return Card( color: Colors.grey, child: Padding( padding: const EdgeInsets.all(5.0), child: Text( 'Separator $position', style: TextStyle(color: Colors.white), ), ), ); }, itemCount: 20, ),
`
**Output:
ListView.custom()
As the name suggests, the ListView.custom() constructor lets us build ListViews with custom functionality for how the children of the list are built. The main parameter of this constructor is a SliverChildDelegate which builds the items.
The types of SliverChildDelegates are :
- **SliverChildListDelegate
- **SliverChildBuilderDelegate
The SliverChildListDelegate accepts a list of children widgets. whereas the SliverChildBuilderDelegate accepts an IndexedWidgetBuilder, simply a builder() function. Digging deeper, we can infer that ListView.builder was created using a ListView.custom with a SliverChildBuilderDelegate. Also, the default ListView() constructor is a ListView.custom with a SliverChildListDelegate.
**Code for ListView.custom() :
Dart `
ListView.custom( childrenDelegate: SliverChildBuilderDelegate( (BuildContext context, int index) { return ListTile( leading: Icon(Icons.person), title: Text('Item $index'), ); }, childCount: 20, // Number of items ), ),
`