Flutter ListView showing only 3 items
In Flutter, you can limit the number of items displayed in a ListView by controlling its itemCount property and applying appropriate logic. Here’s an example:
// Import necessary packages
import 'package:flutter/material.dart';
// Create a sample list of items
List itemList = [
'Item 1',
'Item 2',
'Item 3',
'Item 4',
'Item 5',
'Item 6',
'Item 7',
'Item 8',
'Item 9',
'Item 10'
];
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Flutter ListView Example'),
),
body: ListView.builder(
itemCount: itemList.length >= 3 ? 3 : itemList.length, // Limiting the display to 3 items
itemBuilder: (BuildContext context, int index) {
return ListTile(
title: Text(itemList[index]),
);
},
),
),
);
}
}
In the above example, we have created a ListView.builder widget that dynamically builds the list items based on the itemCount property. Here, the itemCount is set to either 3 or the length of the itemList, whichever is smaller. This way, the ListView will only display a maximum of 3 items even if the itemList contains more elements.