如何在不阻止UI呈现的情况下构建复杂的小部件?

问题描述 投票:0回答:2

我正在建立一个网站的客户端,用户可以以树状方式发布评论。目前,我正在使用以下内容来显示加载栏,直到加载注释。

FutureBuilder(
            future: fetchComments(this.storyId),
            builder: (BuildContext context, AsyncSnapshot snapshot) {
              switch (snapshot.connectionState) {
                case ConnectionState.none:
                case ConnectionState.active:
                case ConnectionState.waiting:
                  return LinearProgressIndicator();
                case ConnectionState.done:
                  if (snapshot.hasError) {
                    final MissingRequiredKeysException myError = snapshot.error;
                    return Text('Error: ${myError.missingKeys}');
                  } else {
                    final api.Comment comment = snapshot.data;

                    return Expanded(child: Comment(comment.comments));
                  }
              }
            }
)

当有大约200条评论时,这种方法非常有效,但是当有超过这条评论时,加载条会“挂起”一段相当长的时间。

我假设构建Comment小部件需要花费大量时间,因为它可以深度嵌套。

为了避免挂起主线程,我修改了我的代码以在Isolate中创建小部件:

FutureBuilder(
            future: compute<int, Widget>(
                buildComments, this.storyId),
            builder: (BuildContext context, AsyncSnapshot snapshot) {
              switch (snapshot.connectionState) {
                case ConnectionState.none:
                case ConnectionState.active:
                case ConnectionState.waiting:
                  return LinearProgressIndicator();
                case ConnectionState.done:
                  if (snapshot.hasError) {
                    final ArgumentError myError = snapshot.error;
                    return Text('Error: ${myError.message}');
                  } else {
                    final Widget comments = snapshot.data;

                    return comments;
                  }
              }
            },
          )

但这甚至更慢,UI被阻止了两倍的时间。我怀疑它可能是由孤立和主隔离之间的数据传输引起的(可能发生在主线程中)。

什么是解决这个悬而未决问题的好方法?

我想让用户尽可能透明(滚动列表时不加载动画)。

dart flutter flutter-layout
2个回答
0
投票

我认为它工作缓慢,因为你将很多对象加载到内存中。我建议你从firebase中加载延迟评论。首先显示用户只有前20条评论,当他滚动到底部时显示20条评论,依此类推。


0
投票

我可以建议你不要使用未来的构建器,每个请求得到200条评论,因为我确定你说解析数据是挂起的主要原因,因为在异步下载完成之后会发生什么,你试图解析发生的数据主队列 - 不是主线程 - 因为flutter是单线程的,所以你能告诉我们你如何解析数据。

© www.soinside.com 2019 - 2024. All rights reserved.