List and onTap
- Flutter course
- Beginner
- Lesson 73/99
- 4 min
Add onTap to a list row and toggle task completion.
onTap on a list row
When a list row is tapped, onTap is used to change the task's completion state. In the ListTile's onTap callback, you toggle the done field of the relevant Todo and rebuild the screen with setState.
ListTile(
title: Text(todo.title),
onTap: () {
setState(() {
todo.done = !todo.done;
});
},
)Toggling the done field
To complete a task, the expression todo.done = !todo.done is used. This turns true into false and false into true. For the change to appear on screen, this operation must be done inside setState; otherwise the screen is not rebuilt.
Practice Complete a task
Write a function complete that takes List<Todo> and int index parameters, sets the done field of the relevant Todo to true, and prints 'Tamamlandi'. In main, create a list with two tasks and call complete with index 0.
Starter code
import 'package:flutter/material.dart';
class Todo {
String title;
bool done;
Todo({required this.title, this.done = false});
}
// tamamla fonksiyonu yaz: List<Todo> ve int index alsin
// ilgili Todo'nun done alanini true yap
// "Tamamlandi" yazdirsin
void main() {
final list = [Todo(title: 'A'), Todo(title: 'B')];
// tamamla'yi cagir
}Sample solution
import 'package:flutter/material.dart';
class Todo {
String title;
bool done;
Todo({required this.title, this.done = false});
}
void tamamla(List<Todo> list, int index) {
list[index].done = true;
print('Tamamlandi');
}
void main() {
final list = [Todo(title: 'A'), Todo(title: 'B')];
tamamla(list, 0);
}Expected output
Tamamlandi
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does setState do?
- Opens the keyboard
- Calls the Navigator
- Rebuilds the widget Correct answer
- Deletes the list
Explanation: setState is used to rebuild the widget after a change in State; it does not open the keyboard, call Navigator, or delete the list.
2 setState call
onTap: () {
____(() {
todo.done = !todo.done;
});
},
onTap: () {
setState(() {
todo.done = !todo.done;
});
},
Explanation: To rebuild the screen after a change in State, setState is called; build, refresh or update do not do the same.
3 onTap and setState parts
| Term | Meaning |
|---|---|
onTap |
Row tap callback |
setState |
Rebuilds the screen |
done |
Completion field |
ListTile |
Row widget |