dart - 在列表视图中向上滚动时,第一项保持重新渲染
问题描述
我遇到了一件烦人的事情,我的列表视图中的第一项在向上滚动时会不断重新渲染。就算我在上面。
我注意到这一点的唯一方法是因为我有一个小部件,它在加载时获取一个 url,并获取元标题、描述和图像,并将其显示在一张漂亮的卡片中。
我的列表视图相当简单:
ListView.builder(
physics: AlwaysScrollableScrollPhysics(),
controller: _scrollController,
itemCount: model.posts.posts.length,
itemBuilder: (context, index) {
// Items goes here
});
我该如何阻止它发生?
不断重新渲染的小部件是一个无状态的小部件,它导入一个 ScopedModel 模型,从互联网获取一些数据,并抓取元数据,然后更新模型。
@override
Widget build(BuildContext context) {
UrlEmbedModel _model = new UrlEmbedModel(); // <-- the ScopedModel
_model.fetchHtml(url); // <-- the url param comes from the constuctor
// Rest of the widget
}
这是从网络获取内容的代码。
void fetchHtml(url) {
http.get(url).then((response) {
if (response.statusCode == 200) {
// If server returns an OK response, parse the JSON
var document = parse(response.body);
var list = document.getElementsByTagName('meta');
for (var item in list) {
if (item.attributes['property'] == "og:title") {
_title = item.attributes['content'];
}
if (item.attributes['property'] == "og:description") {
_description = item.attributes['content'];
}
if (item.attributes['property'] == "og:image") {
_imageUrl = item.attributes['content'];
}
notifyListeners();
}
} else {
// If that response was not OK, throw an error.
throw Exception('Failed to load post');
}
});
}
解决方案
您编写的代码看起来不错,但是发出请求的函数呢?你能展示一下吗?
如果它是一个 Future 函数,它只会发出一次请求然后完成它,它不像一个总是监听事件的流函数。
编辑
首先,如果这个函数发出请求,那么函数的类型必须是Future
,如果不返回任何内容,则为 void 类型,然后添加async
调用。您可以将 .then 方法更改为 await 方法,它会更适合您。
Future<void> fetchHtml(url) async {
final Response response = await get(url);
final dynamic documents = json.decode(response.body); //import 'dart:convert';
print(documents); // print to see what you get than, pass it to the variables you want the data
if (response.statusCode == 200) {
//in here
}
}
我可以在 fetch 请求中看到一些感觉,如果您回答它,我会很高兴:
为什么你不反序列化你收到的 json?
var documents = json.decode(response.body)
您可以在反序列化后打印文档变量并将其归因于您想要的小部件
你这样做的方式并没有错,但可以改进它。
推荐阅读
- highcharts - 如何为高图表中的堆积条添加背景阴影
- azure - 链接服务的 Azure 服务主体名称
- kubernetes - Kubernetes nginx-Ingress 反向代理一些路径
- c# - HttpWebRequest - 无法发送具有此动词类型的内容主体
- python - 如何避免 Scrapy url 被重定向
- mysql - MySQL - 试图过滤掉过去当前时间的日期和时间
- azure - DATEDIFF 溢出
- javascript - 选项:在 jquery 中选择也在隐藏选项中计数
- symfony - 如何为在 services.yaml 外部注册的服务提供参数
- ghostscript - Ghostscript PDF 字体在 Adobe Illustrator 中变成了框,在 Adobe Acrobat 中打开时它的输出很好