I have a ListView.builder
widget in my Flutter app that displays a list of tiles. Each tile has a delete button, and I want to remove the corresponding tile from the ListView when the delete button is clicked.
Here’s a simplified version of my code:
class MyTabView extends StatelessWidget {
// ...
@override
Widget build(BuildContext context) {
// ...
return TabBarView(
children: <Widget>[
ListView.builder(
itemCount: 25,
itemBuilder: (BuildContext context, int index) {
return ListTile(
// ...
title: Row(
children: [
Expanded(
child: Text(
'${titles[0]} $index',
style: const TextStyle(fontSize: 16),
),
),
GestureDetector(
onTap: () {
// How can I delete the corresponding tile when this delete button is clicked?
},
child: const Icon(Icons.delete),
),
],
),
);
},
),
// ...
],
);
}
}
I’m unsure how to implement the functionality to remove the tile from the ListView when the delete button is pressed. Could someone please guide me on how to achieve this?
Feel free to include any additional details or clarifications that might help other developers understand your question better. Good luck with your question on Stack Overflow!
2
Answers
All you need to do is to remove an item from
titles
list at the index you clicked at. In dart to remove something from a list at specific index you can use removeAt method.But, since that won’t do anything on the UI side you need to tell Flutter to redraw your widget again, but this time without that item you previously removed. To do that you can use setState method.
Note: Since you are using some kind of state now you need to change your widget to Stateful widget. Also, since
titles
is missing from provided code I assumed it’s the part of your State class.you need to change a little things things:
StatelessWidget by StatefulWidget
change fixed value of itemCount 25 by length of iterable, like:
and and finally:
example complete: