top of page

Flutter ListView

  • Writer: Priyanka Thakkar
    Priyanka Thakkar
  • Apr 26, 2024
  • 4 min read

Updated: Aug 2, 2024

In Flutter, the ListView widget is a scrollable list of widgets arranged linearly, displaying its children one after another in either the vertical or horizontal scroll direction. It's a crucial widget in Flutter, commonly used for displaying lists of children.

When we need to create lists dynamically without duplicating code, we use ListView.builder instead of ListView. ListView.builder efficiently creates a scrollable, linear array of widgets.

ListView widget for working with lists, which is essential for displaying data in mobile apps. It's ideal for displaying lists containing only a few items. Additionally, ListView includes the ListTile widget, which offers more properties for visually structuring a list of data.


There are different types of flutter ListViews :

  • ListView

  • ListView.builder

  • ListView.separated

  • ListView.custom



ListView vs ListView.Builder

ListView

ListView.Builder

ListView is suitable for displaying a fixed list of widgets.

ListView.builder is more efficient for creating lists with a large number of dynamically generated items.

ListView requires you to provide all the children upfront.

ListView.builder allows you to generate items lazily, as needed, based on an input list or data source




Constructor

ListView Class
ListView(

{Key key,

Axis scrollDirection: Axis.vertical,

bool reverse: false,

ScrollController controller,

bool primary,

ScrollPhysics physics,

bool shrinkWrap: false,

EdgeInsetsGeometry padding,

double itemExtent,

bool addAutomaticKeepAlives: true,

bool addRepaintBoundaries: true,

bool addSemanticIndexes: true,

double cacheExtent,

List<Widget> children: const <Widget>[],

int semanticChildCount,

DragStartBehavior dragStartBehavior: DragStartBehavior.start,

ScrollViewKeyboardDismissBehavior keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.manual,

String restorationId,

Clip clipBehavior: Clip.hardEdge}

)
ListView.builder Class
ListView.builder(

{Key key,

Axis scrollDirection: Axis.vertical,

bool reverse: false,

ScrollController controller,

bool primary,

ScrollPhysics physics,

bool shrinkWrap: false,

EdgeInsetsGeometry padding,

double itemExtent,

@required IndexedWidgetBuilder itemBuilder,

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}

)



Properties of Flutter ListView

children

List of widgets to be displayed in the list. Suitable for a small number of fixed items.

ListView(
  children: [
    Text('Widget 1'),
    Text('Widget 2'),
  ],
)
shrinkWrap

Whether the list should adjust its size to fit the content.

scrollDirection

Determines the direction of scrolling. Default is vertical.

itemExtent

The itemExtent property takes a double value as the object to control the scrollable area in the ListView.

padding

It holds an EdgeInsetsGeometry object to give space between the ListView and its children.

clipBehavior

This property holds a Clip enum (final) as the object. It controls whether the content in the ListView will be clipped or not.


physics

Defines the scrolling behavior. Need to choose from various options like BouncingScrollPhysics, ClampingScrollPhysics, and more, depending on how you want the scrolling to behave.





Properties of ListView.Builder

itemCount

The number of items in the list.

itemBuilder

A builder function that generates widgets for each item in the list.

scrollDirection, shrinkWrap, physics

Similar to ListView properties.





Practice with widget:

ListView Example
Flutter ListView UI Design
Flutter ListView Example
class ListViewExample extends StatelessWidget {
  const ListViewExample({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          backgroundColor: Color(0xff3555c0),
          leading: SvgPicture.asset(
            'assets/image/code_capp1.svg',
            fit: BoxFit.fitWidth,
          ),
          //remove this line
          title: Text('Code Cappuccino', style: TextStyle(color: Colors.white)),
        ),
        body: ListView.builder(
          itemCount: 20, // Number of items in your list
          itemBuilder: (context, index) {
            return ListTile(
              leading: CircleAvatar(
                child: Text('${index + 1}'),
              ),
              title: Text('Item ${index + 1}'),
              subtitle: Text('Subtitle for Item ${index + 1}'),
              onTap: () {
                // Action when item is tapped
                print('Tapped on Item ${index + 1}');
              },
            );
          },
        ),
      ),
    );
  }
}
ListView.Builder Example
How to Use ListView.Builder in flutter
ListView.Builder UI Example
class ListViewBuilderExample extends StatelessWidget {
  const ListViewBuilderExample({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          backgroundColor: Color(0xff3555c0),
          leading: SvgPicture.asset(
            'assets/image/code_capp1.svg',
            fit: BoxFit.fitWidth,
          ),
          //remove this line
          title: Text('Code Cappuccino', style: TextStyle(color: Colors.white)),
        ),
        body: ListView(
          children: const [
            ListTile(
              title: Text('Item 1'),
              subtitle: Text('This is a subtitle for item 1'),
              leading: Icon(Icons.account_box),
              trailing: Icon(Icons.arrow_forward_ios),
            ),
            ListTile(
              title: Text('Item 2'),
              subtitle: Text('This is a subtitle for item 2'),
              leading: Icon(Icons.settings),
              trailing: Icon(Icons.more_vert),
            ),
            ListTile(
              title: Text('Item 3'),
              subtitle: Text('This is a subtitle for item 3'),
              leading: Icon(Icons.star),
            ),
          ],
        ),
      ),
    );
  }
}
ListView.separated Example
Flutter Listview.seprated Example, how to use
ListView.separated

class ListViewSeparatedExample extends StatelessWidget {
  const ListViewSeparatedExample({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          backgroundColor: Color(0xff3555c0),
          leading: SvgPicture.asset(
            'assets/image/code_capp1.svg',
            fit: BoxFit.fitWidth,
          ),
          //remove this line
          title: Text('Code Cappuccino', style: TextStyle(color: Colors.white)),
        ),
        body: ListView.separated(
          itemCount: 10,
          separatorBuilder: (context, index) => const Divider(
            color: Colors.grey,
            thickness: 1,
          ),
          itemBuilder: (context, index) {
            return ListTile(
              leading: Icon(Icons.star),
              title: Text('Item ${index + 1}'),
            );
          },
        ),
      ),
    );
  }
}
ListView.Custom Example
How to use ListView.custom with SliverChildBuilderDelegate
Flutter ListView.custom
class ListViewCustomExample extends StatelessWidget {
  const ListViewCustomExample({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'ListView.custom Example',
      home: Scaffold(
        appBar: AppBar(
          backgroundColor: Color(0xff3555c0),
          leading: SvgPicture.asset(
            'assets/image/code_capp1.svg',
            fit: BoxFit.fitWidth,
          ),
          //remove this line
          title: Text('Code Cappuccino', style: TextStyle(color: Colors.white)),
        ),
        body: ListView.custom(
          childrenDelegate: SliverChildBuilderDelegate(
                (context, index) {
              return ListTile(
                leading: Icon(Icons.star),
                title: Text('Item ${index + 1}'),
              );
            },
            childCount: 10,
          ),
        ),
      ),
    );
  }
}

Dynamic ListView

Flutter ListView Set Dynamic Data
Flutter ListView
class Products {
  String image;
  String title;
  String subtitle;
  String date;

  Products(
      {required this.date,
        required this.image,
        required this.subtitle,
        required this.title});
}




class ListAllPage extends StatefulWidget {
  const ListAllPage({super.key});

  @override
  State<ListAllPage> createState() => _ListAllPageState();
}

class _ListAllPageState extends State<ListAllPage> {
  List<Products> productDetails = [
    Products(
        date: '16 June,2023',
        image:
        'https://picsum.photos/id/241/200/300',
        subtitle: 'This is description text',
        title: 'Switches'),
    Products(
        date: '7 February, 2021',
        image:
        'https://picsum.photos/id/42/200/300',
        subtitle: 'This is description text',
        title: 'Air-Conditioner'),
    Products(
        date: '3 July,2018',
        image:
        'https://picsum.photos/id/55/200/300',
        subtitle: 'This is description text',
        title: 'DoorBell'),
    Products(
        date: '9 May, 2020',
        image:
        'https://picsum.photos/id/1/200/300',
        subtitle: 'This is description text',
        title: 'Security'),
    Products(
        date: '21 December, 2022',
        image:
        'https://picsum.photos/id/58/200/300',
        subtitle: 'This is description text',
        title: 'Sensors'),
  ];

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          backgroundColor: Color(0xff3555c0),
          leading: SvgPicture.asset(
            'assets/image/code_capp1.svg',
            fit: BoxFit.fitWidth,
          ),
          //remove this line
          title: Text('Code Cappuccino', style: TextStyle(color: Colors.white)),
        ),
        body: ListView.separated(
          itemCount: productDetails.length,
          separatorBuilder: (context, index) => Divider(),
          itemBuilder: (context, index) {
            final currentProduct = productDetails[index];
            return ListTile(
              leading: Image.network(
                width: 100,
                height: 100,
                currentProduct.image,
                fit: BoxFit.cover,
              ),
              title: Text(currentProduct.title),
              subtitle: Text(currentProduct.subtitle),
              trailing: Column(
                children: [
                  Text(currentProduct.date),
                ],
              ),
            );
          },
        ),
      ),
    );
  }
}


Comments


bottom of page