Flutter

How to use ListView.builder in flutter

To use ListView.builder in Flutter for creating dynamic and potentially long lists, follow these steps: Import the Material package.

Code

    import 'package:flutter/material.dart';
  • Create a data source: This can be a List of strings, objects, or any data you want to display.

Code

    final List<String> items = List<String>.generate(100, (i) => 'Item $i');
  • Implement ListView.builder within your build method:

Code

    class MyListViewScreen extends StatelessWidget {
final List<String> items = List<String>.generate(100, (i) => 'Item $i');

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('ListView.builder Example'),
),
body: ListView.builder(
itemCount: items.length, // Required: Number of items in the list
itemBuilder: (BuildContext context, int index) {
// Required: Function to build each item
return Card(
margin: const EdgeInsets.all(8.0),
child: ListTile(
leading: CircleAvatar(child: Text('${index + 1}')),
title: Text(items[index]),
subtitle: Text('Details for ${items[index]}'),
onTap: () {
// Handle item tap
print('Tapped on ${items[index]}');
},
),
);
},
),
);
}
}

Explanation of key properties:

  • itemCount: This required property specifies the total number of items in your list. It should be the length of your data source.
  • itemBuilder: This is a required callback function that takes BuildContext context and int index as arguments. For each index from 0 to itemCount - 1, this function is called to build the widget for that specific item. You return the widget you want to display for each item in the list.

Benefits of ListView.builder:

  • Performance: It builds items on demand, meaning only the widgets currently visible on screen (and a few extra for smooth scrolling) are rendered. This is highly efficient for large or infinite lists, as it avoids building all widgets at once.
  • Dynamic Lists: It easily handles lists where the number of items can change dynamically.

Also Read:-

Flutter key points mostly asked in flutter interviews
Dart basic programs mostly asked in interviews

Leave a Reply

Your email address will not be published. Required fields are marked *