I press the button to add a ListTile widget to the list and output it to the ListViewBuilder. And I want to delete the list by pressing the delete button on each list.
List<ListTile> _todoList = [];
Add List Button
TextButton.icon(
onPressed: () {
//I wrote the text in a TextField in the Dialog Widget.
//And add ListTile widget to list
_todoList.add(_addListTile(_textController.text));
}
Output list
ListView.builder(
itemBuilder: (context, index) {
return _todoList[index];
},
itemCount: _todoList.length),
This is a widget that is added to the list. And I want to delete the index of the list by pressing the button on the list tile.
_addListTile(String text) {
return ListTile(
title: Text(text),
//menu
trailing: PopupMenuButton(
// icon: const Icon(Icons.more_vert),
itemBuilder: (context) {
return [const PopupMenuItem<int>(value: 0, child: Text('Remove'))];
},
//Cliked menu
onSelected: (item) {
switch (item) {
case 0:
return print('Remove List');
// return _todoList.remove();
}
},
),
onTap: () {},
);
}
How can I delete the list with the delete button on this ListTile?
Thank you.
CodePudding user response:
I think you can put a key
value to each ListTile
object to identify which ListTile is the one you want to delete everytime you generate it in your _addListTile()
function like following.
_addListTile(String text) {
// You can have anything to be the unique value. Here, I just used the current time.
// I can't say this is the best option.
final key = ValueKey(DateTime.now().toString());
return ListTile(
key: key,
title: Text(text),
//menu
trailing: PopupMenuButton(
// icon: const Icon(Icons.more_vert),
itemBuilder: (context) {
return [const PopupMenuItem<int>(value: 0, child: Text('Remove'))];
},
//Cliked menu
onSelected: (item) {
switch (item) {
case 0:
print('Remove List');
return _todoList.removeWhere((e) => e.key == key);
}
},
),
onTap: () {},
);
}
I hope it'd work for you.