简体   繁体   English

在 Flutter 中构建动态列表的最有效方法是什么?

[英]What is the most efficient way of building a dynamic list in Flutter?

So, I am currently attempting to build a list dynamically in my app by using listview.builder.所以,我目前正在尝试使用 listview.builder 在我的应用程序中动态构建一个列表。 I was originally planning on sending an http request to load only a few items at a time, but I had a lot of trouble with using both futurebuilder and listview builder.我最初计划发送一个 http 请求一次只加载几个项目,但是我在使用 futurebuilder 和 listview builder 时遇到了很多麻烦。 The idea was that if the user scrolled to the bottom then more items were loaded.这个想法是,如果用户滚动到底部,则会加载更多项目。 Now I'm using a streambuilder and the backend sends all items at once, which I believe is inefficient, but because I am inexperienced with building lists from streams I can't tell for sure.现在我正在使用流构建器,后端一次发送所有项目,我认为这是低效的,但是因为我没有从流构建列表的经验,所以我无法确定。 Anyhow, I would like some recommendations for building long lists dynamically.无论如何,我想要一些动态构建长列表的建议。

The best way to do this should be by using ListView.builder.最好的方法是使用 ListView.builder。 To use ListView.builder, you have to create an instance of it by calling its constructor using new, it takes multiple parameters.要使用 ListView.builder,您必须通过使用 new 调用其构造函数来创建它的实例,它需要多个参数。 Assume that we have a global list like this in our application假设我们的应用程序中有一个这样的全局列表

List<String> litems = ["1","2","Third","4"];

Using LIstView.builder, the code for the same shall look like this使用 LIstView.builder,相同的代码应如下所示

body: new ListView.builder
  (
    itemCount: litems.length,
    itemBuilder: (BuildContext ctxt, int index) {
     return new Text(litems[index]);
    }
  )

In here, the in-place callback function shall be called 4 times and each call will generate a Text Widget which shall be displayed in the body.在这里,就地回调 function 将被调用 4 次,每次调用都会生成一个 Text Widget,该控件将显示在 body 中。

You can also write a separate function which can be called from itemBuilder as您还可以编写一个单独的 function 可以从 itemBuilder 调用为

// A Separate Function called from itemBuilder
Widget buildBody(BuildContext ctxt, int index) {
  return new Text(litems[index]);
}
body: new ListView.builder
(
  itemCount: litems.length,
  itemBuilder: (BuildContext ctxt, int index) => 
buildBody(ctxt, index)
),

In both cases, the output will look the same.在这两种情况下,output 看起来都一样。 You can also use ListView.builder(..) in Stateless Widgets if you want to display dynamic (different) contents every time the widget is loaded within an application.如果您希望每次在应用程序中加载小部件时都显示动态(不同)内容,您还可以在无状态小部件中使用 ListView.builder(..)。 With Stateful widgets, it can change the contents of the screen dynamically.使用有状态的小部件,它可以动态地改变屏幕的内容。 I hope this helps我希望这有帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM