Tap a List Tile
Part of the Lists and Screens section of Coddy's Flutter journey. Lesson 4 of 33.
A list is more than something to read: you tap a row to pick it. ListTile has an onTap:, a function that runs when the row is tapped, the same idea as a button's onPressed:.
ListTile(
title: Text(fruit),
onTap: () {
setState(() {
picked = fruit;
});
},
)A tile with an onTap: also shows a ripple when you touch it, so it feels like a button.
When the tiles are made by a for, each tile's onTap remembers its own fruit. Tapping Kiwi runs Kiwi's function, with fruit set to 'Kiwi'.
Challenge
EasyThe app bar says Pick a fruit. Give every tile an onTap: so tapping a fruit changes the app bar to You picked Mango (with the fruit that was tapped).
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) {
return const MaterialApp(
debugShowCheckedModeBanner: false,
home: FruitPicker(),
);
}
}
class FruitPicker extends StatefulWidget {
const FruitPicker({super.key});
@override
State<FruitPicker> createState() => _FruitPickerState();
}
class _FruitPickerState extends State<FruitPicker> {
final List<String> fruits = ['Apple', 'Banana', 'Kiwi', 'Mango', 'Peach'];
String picked = 'Pick a fruit';
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text(picked)),
body: ListView(
children: [
for (String fruit in fruits)
ListTile(
title: Text(fruit),
),
],
),
);
}
}
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