首页 > 解决方案 > 在列表视图中向上滚动时,第一项保持重新渲染

问题描述

我遇到了一件烦人的事情,我的列表视图中的第一项在向上滚动时会不断重新渲染。就算我在上面。

我注意到这一点的唯一方法是因为我有一个小部件,它在加载时获取一个 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');
    }
  });
}

标签: dartflutter

解决方案


您编写的代码看起来不错,但是发出请求的函数呢?你能展示一下吗?

如果它是一个 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 请求中看到一些感觉,如果您回答它,我会很高兴:

  1. 为什么你不反序列化你收到的 json?

    var documents = json.decode(response.body)

  2. 您可以在反序列化后打印文档变量并将其归因于您想要的小部件

你这样做的方式并没有错,但可以改进它。


推荐阅读