Lists and grids are essential for displaying collections of data in a structured and organized way in your Flutter app. In this tutorial, we'll explore how to work with lists and grids using various widgets and examples.
1. Working with Lists
1.1. ListView
'ListView' is one of the most common widgets for displaying lists of data. It can be used in various modes, including vertical scrolling, horizontal scrolling, and grid-like layouts.
In this example, we generate a list of items dynamically and use 'ListView.builder' to display them.
3. Adding Interactivity to Lists and Grids
You can make your lists and grids interactive by adding tap gestures or other user interactions.
Example: Tappable List Items
class TappableListItemsExample extends StatelessWidget {
final List items = List.generate(50, (index) => 'Item $index');
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Tappable List Items Example'),
),
body: ListView.builder(
itemCount: items.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(items[index]),
onTap: () {
// Handle item tap here
print('Tapped on Item $index');
},
);
},
),
);
}
}
In this example, we make the list items tappable by adding an 'onTap' callback to each 'ListTile'.
4. Customizing List and Grid Items
You can customize the appearance of list and grid items using various widgets, including 'Card', 'InkWell', or your custom widgets.
Example: Custom List with 'Card'
class CustomListExample extends StatelessWidget {
final List items = List.generate(50, (index) => 'Item $index');
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Custom List Example'),
),
body: ListView.builder(
itemCount: items.length,
itemBuilder: (context, index) {
return Card(
elevation: 4.0,
margin: EdgeInsets.all(8.0),
child: ListTile(
title: Text(items[index]),
subtitle: Text('Subtitle for Item $index'),
leading: Icon(Icons.star),
trailing: Icon(Icons.arrow_forward),
onTap: () {
// Handle item tap here
print('Tapped on Item $index');
},
),
);
},
),
);
}
}
In this example, we create a custom list with 'Card' and customize each list item with a title, subtitle, leading and trailing icons.
Conclusion:
Lists and grids are essential components of most Flutter apps, allowing you to display and interact with various types of data. By using widgets like 'ListView', 'GridView', 'ListTile', and custom widgets, you can create organized and interactive user interfaces. Experiment with different layouts, interactivity, and customization options to meet your app's specific requirements.