I am working with APIs and using a delete method to delete an item with a unique id from a list. The delete method is working but I need to reload the page everytime I want to see the results. I tried to add a setState() function inside a button and call the delete method from there but it is not working. I am not getting any errors however.
Delete method:
Future <void> deleteData(todo) async {
var urlToUpdate = Uri.parse('https://todoapp-api.apps.k8s.gu.se/todos/${todo.id}?key=${testKey}');
try {
await http.delete(urlToUpdate, headers: {"Content-Type": "application/json"}, body: jsonEncode({
"id": todo.id,
"title": todo.title,
"done": todo.done
}));
} catch (err) {
print(err);
}
}
setState method:
child: IconButton(
onPressed: () {
setState(() {
var deleteTodo = TodoItem(id: id, title: '', done: false);
deleteData(deleteTodo);
});
},
I can’t provide the whole code because it is too large but the delete method comes right after :
class _TodoListState extends State {
and before initState and Widget build.
My TodoItemsList works like this:
Future fetchPosts() async {
try {
await getKey();
final response = await HTTP.get(Uri.parse('${url}${todos}${testKey}'));
final jsonData = jsonDecode(response.body);
setState(() {
TodoItemsList = jsonData;
});
print(jsonData);
} catch (err) {
print('Error');
}
}
This empty list is just above the Widget build
List TodoItemsList = [];
This widget is inside by body property:
Widget getBody() {
return ListView.builder(
itemCount: TodoItemsList.length,
itemBuilder: (context, index) {
return getCard(TodoItemsList[index]);
});
}
2
Answers
setState method is used to reflect any change of data over some widget, if you need to remove a element from a list need has that element linked to a widget
example:
If you has
then
If you notice listOfMovie is linked to ListView widget
you should wait until the deleteData finished.
After that, remove the local TodoItem from the list by yourself.
Because network request usually takes times. You should display something like
CircularProgressIndicator
whendeleteData
is running. But that’s another story.