简体   繁体   English

为什么 flutter 中的 setState function 不起作用?

[英]Why is setState function in flutter not working?

I am working with APIs and using a delete method to delete an item with a unique id from a list.我正在使用 API 并使用删除方法从列表中删除具有唯一 ID 的项目。 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.我试图在按钮内添加一个 setState() function 并从那里调用删除方法,但它不起作用。 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 { class _TodoListState 扩展 State {

and before initState and Widget build.在 initState 和 Widget 构建之前。

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 setState方法用于反映某些小部件上的任何数据更改,如果您需要从列表中删除元素,则需要将该元素链接到小部件

example: If you has例子:如果你有

listOfMovie = ['Avatar, Avengers', 'Dune', 'Hulk'];
ListView.builder(
                itemCount: listOfMovie.length,
                itemBuilder: (_, index) => Text(listOfMovie[index],
));

then然后

child: IconButton(
                  onPressed: () {
                   setState(() {
                   listOfMovie = ['Avatar, Avengers'];                   
                });
              },

If you notice listOfMovie is linked to ListView widget如果您注意到 listOfMovie 链接到 ListView 小部件

you should wait until the deleteData finished.你应该等到 deleteData 完成。

After that, remove the local TodoItem from the list by yourself.之后,自行从列表中删除本地 TodoItem。

child: IconButton(
  onPressed: () async {
    var deleteTodo = TodoItem(id: id, title: '', done: false);
    await deleteData(deleteTodo);
    setState(() {
      => remove TodoItem from the local list =<
    });
  }

Because network request usually takes times.因为网络请求通常需要时间。 You should display something like CircularProgressIndicator when deleteData is running.deleteData运行时,您应该显示类似CircularProgressIndicator的内容。 But that's another story.但那是另一回事了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM