Delete and divider
- Flutter course
- Beginner
- Lesson 74/99
- 4 min
Add swipe to delete and row dividers.
Deleting with Dismissible
To delete by swiping, the Dismissible widget is used. Dismissible wraps its child and calls the onDismissed callback when the user swipes it left or right. Each Dismissible must be given a unique key.
Dismissible(
key: ValueKey(todo.title),
onDismissed: (direction) {
setState(() {
list.removeAt(index);
});
},
child: ListTile(...),
)Separator with Divider
To put a separator between list rows, ListView.separated and Divider are used. The separatorBuilder draws a widget between each row; usually a Divider is given. This visually separates the rows.
Practice Delete by swipe
Write a function delete that takes List<Todo> and int index parameters, removes the element at that index, and prints 'Silindi'. In main, create a list with two tasks and call delete with index 0.
Starter code
import 'package:flutter/material.dart';
class Todo {
String title;
bool done;
Todo({required this.title, this.done = false});
}
// sil fonksiyonu yaz: List<Todo> ve int index alsin
// ilgili elemani listeden cikar
// "Silindi" yazdirsin
void main() {
final list = [Todo(title: 'A'), Todo(title: 'B')];
// sil'i cagir
}Sample solution
import 'package:flutter/material.dart';
class Todo {
String title;
bool done;
Todo({required this.title, this.done = false});
}
void sil(List<Todo> list, int index) {
list.removeAt(index);
print('Silindi');
}
void main() {
final list = [Todo(title: 'A'), Todo(title: 'B')];
sil(list, 0);
}Expected output
Silindi
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which parameter of Dismissible must be given a unique value?
- shape
- key Correct answer
- padding
- color
Explanation: Dismissible must be given a unique key; color, shape and padding do not need to be unique.
2 Add onDismissed to Dismissible
Dismissible(
key: ValueKey(todo.title),
____: (direction) {
list.removeAt(index);
},
child: ListTile(...),
)
Dismissible(
key: ValueKey(todo.title),
onDismissed: (direction) {
list.removeAt(index);
},
child: ListTile(...),
)
Explanation: To be called when the swipe completes, onDismissed is used; onTap, onPressed or onLongPress do not capture the swipe event.
3 Delete and separator parts
| Term | Meaning |
|---|---|
Dismissible |
Provides swipe to delete |
key |
Dismissible's unique id |
Divider |
Row separator line |
ListView.separated |
List with separator |