英文:
Flutter Update ListView.builder based on a variable
问题
我有一个相当简单的问题。当我更改从服务器获得的变量的赋值时,我希望listview.builder重新渲染屏幕。这是我当前屏幕的样子:(图片链接)
(每篇新闻文章(由白色sizedbox分隔)基于名为_posts的变量呈现-当此变量更新时,我希望所有新闻小部件更新)
编辑:例如,当用户点击心形图标时,我向服务器发送请求,告诉它用户喜欢这篇新闻文章,当它返回更新的喜欢列表时,我希望图标根据服务器返回的内容变色或不变色。
更多信息:
- 小部件位于listview.builder内
- 我的类扩展了一个有状态小部件
- 服务器返回一个JSON对象
- 我已经在这上面工作了8个小时以上,但无法弄清楚
非常感谢!
示例代码:
这是我的心形图标的样子。当用户点击心形图标时,它告诉服务器,用户不再喜欢这篇文章,并获得更新后的喜欢列表。然而,当我执行setState(() => {liked=(服务器响应的喜欢)})时,它不会更新视图。
(代码)
英文:
I have a pretty simple problem. When I change a variable that gets assigned from a get request to my server, I want the listview.builder to rerender the screen. This is what my screen looks like currently:
(each news article (separated by a white sizedbox) is rendered based on a variable called _posts - when this variable gets updated I want all the news widgets to update)
EDIT: For example when the user clicks the heart icon, I send a request to the server to tell it that the user liked the news article, and when it comes back with the updated liked list, I want the icon to be colored in or not based on what the server returns
MORE INFO
- The widgets are inside a listview.builder
- My class extends a stateful widget
- The server returns a json object
- I've been working on this for 8+ hours and can't figure it out
Thank you so much!
EXAMPLE CODE:
This is what my heart icon looks like. When the user clicks on the heart icon, it tells the server that the post is not liked anymore, and gets the updated liked list. However, when I do a setState(() => {liked=(SERVER RESPONSE LIKED)}), it doesn't update the view.
Icon(
liked.contains(_posts[index]['id'].toString())
? Icons.favorite : Icons.favorite_border, color: Colors.white))
答案1
得分: 1
尝试在点击心形图标后再次调用GET API并且不要忘记清除当前列表,否则会得到重复的数据。使用三元运算符(条件 ? Text("红心") : Text("普通心"),) 也请尝试分享一些代码,这将帮助我理解到底做了什么。
英文:
Try to call GET API again after getting response on tap of heart icon & don't forgot to clear current list or else you will get duplicate data. Use ternary operator (condition ? Text("Red Heart") : Text("Normal Heart"),)
Also try to share some code, it will help me to understand what exactly has done.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论