草庐IT

firebase - Flutter ListView 跳转到顶部

coder 2023-05-09 原文

我正在为我的应用创建新闻提要,当我向下滚动时,将从 Firestore 获取数据。一旦我向上滚动, ListView 就会立即捕捉到最顶部,从而跳过中间的所有其他项目。如果我用静态数据加载 ListView ,它可以正常工作,但是当我从 Firestore 中提取数据时,问题再次出现。我不确定是什么导致了这种行为。

Video demonstrating the irregular scrolling behaviour

这是我的代码

return StreamBuilder(
            stream: Firestore.instance.collection(Constants.NEWS_FEED_NODE)
                .document("m9yyOjsPxV06BrxUtHdp").
            collection(Constants.POSTS_NODE).orderBy("timestamp",descending: true).snapshots(),
            builder: (BuildContext context, AsyncSnapshot snapshot) {
              if (!snapshot.hasData)
                return Center(child: CircularProgressIndicator(),);

              if (snapshot.data.documents.length == 0)
                return Container();
              //after getting the post ids, we then make a call to FireStore again
              //to retrieve the details of the individual posts
              return ListView.builder(
                  itemCount: snapshot.data.documents.length,
                  itemBuilder: (_, int index) {
                    return FeedItem2(feed: Feed.fireStore(
                        snapshot: snapshot.data.documents[index]),);
                  });
            },
          );

最佳答案

问题原因:

ListView, and ScrollViews in general, tend to dispose of the children that are not currently visible on the screen. When we try to scroll back to the child, the child is reinitialized from scratch. But in this case, our child is a FutureBuilder; re-initializing it creates a progress indicator again just for a part of a second, then creates the page once again. This confuses the scrolling mechanism, throwing us around in non-deterministic ways.

Solution :

One way to solve this is to make sure that the progress indicator has the exact same size of the page, but in most cases, that is not too practical. So, we will resort to a method that is less efficient, but that will solve our problems; we will prevent ListView from disposing of the children. In order to do that, we need to wrap each child — that is, each FutureBuilder, with an AutomaticKeepAliveClientMixin. This mixin makes the children ask their parent to keep them alive even when off-screen, which will solve our problem. So:

  1. 将代码中的 FutureBuilder 替换为 KeepAliveFutureBuilder。
  2. 创建 KeepAliveFutureBuilder 小部件:
class KeepAliveFutureBuilder extends StatefulWidget {

  final Future future;
  final AsyncWidgetBuilder builder;

  KeepAliveFutureBuilder({
    this.future,
    this.builder
  });

  @override
  _KeepAliveFutureBuilderState createState() => _KeepAliveFutureBuilderState();
}

class _KeepAliveFutureBuilderState extends State<KeepAliveFutureBuilder> with AutomaticKeepAliveClientMixin {
  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: widget.future,
      builder: widget.builder,
    );
  }

  @override
  bool get wantKeepAlive => true;
}
  • 这个小部件只是 FutureBuilder 的一个包装器。它是一个 StatefulWidget,其 State 使用 AutomaticKeepAliveClientMixin 扩展了 State 类。
  • 它实现了 wantKeppAlive getter,并使其简单地返回 true,以向 ListView 表示我们希望这个 child 保持事件状态。

关于firebase - Flutter ListView 跳转到顶部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51536756/

有关firebase - Flutter ListView 跳转到顶部的更多相关文章

  1. ruby-on-rails - 我需要从 HTML 转到 markdown,有什么建议吗? - 2

    我正在使用Maruku,将Markdown(超集)转换为HTML,你知道我该怎么做才能从HTML转换为Markdown吗? 最佳答案 Google发现了一个名为reverse_markdown的ruby​​脚本.它似乎可以满足您的需求。 关于ruby-on-rails-我需要从HTML转到markdown,有什么建议吗?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/175162

  2. ruby - 是否有任何命令可以使用 vim 转到 Ruby block 的末尾(或开始) - 2

    有没有办法使用vim结束Rubyblock?例如moduleSomeModule#defsome_methodendend我想用一个命令从光标所在的位置移动到block的末尾,这可能吗?我读过thisdocumentation,但它似乎不适用于.rb文件,我在某些地方读到它只适用于C(虽然还没有尝试过)。提前致谢。 最佳答案 rubyforge好像有官方包对此有一些支持:TheRubyftpluginnowincludesRubyspecificimplementationsforthe[[,]],[],][,[m,]m,[M,an

  3. ruby - 在 Vim 中使用 Ctags 跳转到 Ruby bang 方法 - 2

    我在使用ExhuberantCtags跳转到Rubybang方法时遇到问题。我已经搜索过其他有类似问题的人,但找不到任何东西。可以使用以下小型Rub​​y类显示该问题的示例:classHellodefstartmethod!enddefmethod#Blahenddefmethod!#Blahendend当ctags-R.在此文件上运行时,生成的tags文件包含以下两行,表明这两种方法都是在生成时发现的:methodtest.rb/^defmethod$/;"fclass:Hellomethod!test.rb/^defmethod!$/;"fclass:Hello但是,如果我将光标放

  4. 微信小程序顶部标题栏与胶囊对齐 - 2

    介绍    最近在做微信小程序时,顶部标题栏总是与胶囊对不齐。往往是在这款手机上对齐了,在另外一款手机差很多。我在查阅资料后,提出了一种方法解决这个问题,即:在页面onLoad或组件created时,利用微信小程序提供的API,获取系统状态栏高度和胶囊信息,进而动态调整顶部标题栏样式。在苹果、小米、荣耀手机做验证,能做到精准对齐。理论        胶囊样式应该是垂直居中,有1px的border,border-radius为18px。        若要使顶部标题栏与胶囊对齐,则其高度必须是导航栏高度,标题栏内容也要垂直居中,顶部标题栏的外边距或内边距必须是状态栏高度。        如果顶部

  5. ruby - “运行失败跳转到方法定义”错误 : undefined method `current_line' for TextMate:Module - 2

    更新:我想通了。Ctrl-F仅在未选择我正在搜索的方法时有效。游标只需要在方法名中。我刚升级到TextMate2。当我选择一个方法并使用Ctrl+F转到它的定义时,我得到:>FailurerunningJumptoMethodDefinition这是痕迹:/Users/ilikepie/Library/ApplicationSupport/TextMate/Managed/Bundles/RubyonRails.tmbundle/Support/lib/rails/text_mate.rb:54:in`method_missing':undefinedmethod`current_li

  6. ruby - Firebase token 错误, "The custom token corresponds to a different audience." - 2

    我正在尝试在服务器上使用Ruby为Firebase生成JWTtoken。在3.0之前我们使用tokengenerator但升级后它停止工作。我用下面的代码得到的token给出了一个错误:Thecustomtokencorrespondstoadifferentaudience.我到处都找不到它的意思。private_key=OpenSSL::PKey::RSA.new谢谢 最佳答案 我也遇到了这个错误,我得到它是因为我使用了一个与firebase项目无关的服务帐户。在firebase项目下使用新key创建新服务帐户后,它开始工作。要

  7. ruby - 如何使用 Vim 从 do 跳转到 Ruby block 的末尾? - 2

    我正在使用vim进行ruby​​、php和perl开发。有快捷方式%可以从block(子例程/函数/方法/if)的开头跳转到结尾,反之亦然。对我来说,ruby中的do/end标记上的%不起作用。我如何用vim做到这一点? 最佳答案 matchitplugin允许匹配的不仅仅是括号和注释。可以找到ruby​​版本here. 关于ruby-如何使用Vim从do跳转到Rubyblock的末尾?,我们在StackOverflow上找到一个类似的问题: https://

  8. 如何以android中的数组的形式获取firebase中节点的数据 - 2

    以这种格式,我在Firebase中有一个数据库。我必须以阵列列表的形式显示所有部门,例如导演,体育。代码:mAuth=FirebaseAuth.getInstance();mdatabase=FirebaseDatabase.getInstance().getReference().child("Department");mdatabase.addValueEventListener(newValueEventListener(){@OverridepublicvoidonDataChange(DataSnapshotdataSnapshot){ListDepartment=(ArrayLis

  9. ruby - 如何删除 YAML 文件顶部的 '---'? - 2

    我正在用Ruby修改YAML文件。在我写回修改后的YAML后,我看到在文件顶部添加了一个---。这是如何添加的以及如何删除它? 最佳答案 YAMLspec说:YAMLusesthreedashes(“---”)toseparatedirectivesfromdocumentcontent.Thisalsoservestosignalthestartofadocumentifnodirectivesarepresent.例子:#Rankingof1998homeruns----MarkMcGwire-SammySosa-KenGrif

  10. ruby - 我怎样才能避免在 Ruby 1.9 中的每个 UTF-8 文件的顶部放置神奇的编码注释? - 2

    我有一个Rails项目,里面有很多西里尔字符串。它在Ruby1.8上运行良好,但Ruby1.9假定源文件是US-ASCII编码的,除非您在源文件顶部提供#encoding:utf-8注释。此时文件不被视为US-ASCII。是否有更简单的方法告诉Ruby“此应用程序是UTF8编码的。请将所有和任何包含的源文件视为UTF8,除非另有声明”?更新:我写了“Howtoinserttheencoding:UTF-8directiveautomaticallyinRuby1.9files”,它会在需要时自动附加编码指令。 最佳答案 我觉得你可以

随机推荐