Introduction
In Flutter, ListView is a powerful widget used to display scrollable lists of items. Combined with ListTile, you can create clean, consistent list items with text, icons, and actions. This tutorial will guide you through building a simple scrollable list.
Step 1: Creating a New Flutter Project
Open your terminal and run:
flutter create listview_example
Navigate into the project:
cd listview_example
Step 2: Basic ListView Example
Open lib/main.dart
and replace its content with:
</p> import 'package:flutter/material.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( title: 'ListView Example', theme: ThemeData(primarySwatch: Colors.blue), home: const MyHomePage(), ); } } class MyHomePage extends StatelessWidget { const MyHomePage({super.key}); final List<String> items = const [ 'Apple', 'Banana', 'Cherry', 'Grapes', 'Mango', 'Orange' ]; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Fruits List')), body: ListView.builder( itemCount: items.length, itemBuilder: (context, index) { return ListTile( leading: const Icon(Icons.local_grocery_store), title: Text(items[index]), subtitle: const Text('Tap to learn more'), trailing: const Icon(Icons.arrow_forward_ios, size: 16), onTap: () { ScaffoldMessenger.of(context).showSnackBar( SnackBar(content: Text('You tapped on ${items[index]}')), ); }, ); }, ), ); } } <p data-start="857" data-end="907">
Step 3: How This Works
-
ListView.builder efficiently creates only the list items visible on the screen.
-
ListTile provides a ready-to-use layout with:
-
leading
: An icon or avatar. -
title
: Main text. -
subtitle
: Additional description. -
trailing
: Icon or action button. -
onTap
: What happens when the item is tapped.
-
Step 4: Running the App
Run the following command:
flutter run
You should now see a scrollable list of fruits. Tapping an item will show a message.
Key Takeaways
-
ListView is the go-to widget for scrollable content.
-
Use ListTile for quick, consistent item layouts.
-
ListView.builder is ideal for long or dynamic lists because it only builds items when needed.