Numbering the Rows
Part of the Lists and Screens section of Coddy's Flutter journey. Lesson 7 of 33.
The index the builder gets is more than a way to find the right song. It is the row's place in the list, so you can show it.
itemBuilder: (context, index) {
return ListTile(
leading: Text('$index'),
title: Text(songs[index]),
);
},That shows 0 next to the first song, because counting in Dart starts at 0. People count from 1, so show index + 1. A calculation inside a string goes in curly braces: '${index + 1}'.
Challenge
EasyNumber the songs: give each ListTile a leading: CircleAvatar with the song's number, starting at 1 for Morning Light.
Try it yourself
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
final List<String> songs = [
'Morning Light',
'Paper Planes',
'City Rain',
'Slow River',
'Neon Nights',
'Golden Hour',
'Northern Wind',
'Blue Harbor',
'Quiet Storm',
'Summer Static',
'Echo Valley',
'Last Train',
'Silver Lines',
'Open Road',
'Starfall',
];
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
appBar: AppBar(title: const Text('Playlist')),
body: ListView.builder(
itemCount: songs.length,
itemBuilder: (context, index) {
return ListTile(title: Text(songs[index]));
},
),
),
);
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Lists and Screens
1Scrolling Lists
A List That ScrollsList TilesLeading and TrailingTap a List TileDividers Between Rows6Tabs, Drawers and Swipes
Tabs With a Navigation BarFilled Icons for the Open TabA Side DrawerSwipe to DeleteUndo a SwipePractice on your own: Online Flutter compiler