2

我想要一个包含来自 Stream 的项目的 ListView。当然,List 的内容应该反映 Stream 的变化。由于我的设计师怪癖,我希望列表中的项目用分隔线分隔。

只是想知道,用分隔符创建 ListView 并对 Stream 更改做出反应的正确方法是什么。

body: StreamBuilder(
        stream: someStream,
        builder: (ctx, snapshot) {
          return ListView.separated(
            separatorBuilder: (context, index) => Divider(color: Colors.black),
            itemCount: ***whatsHere***?,
            itemBuilder: (BuildContext ctx, int index) {
...

希望我错过了什么。由于以某种方式获得源流长度的想法至少看起来很奇怪,因为流的异步性质。使用流订阅(和 setState 调用)的 StatefullWidget 似乎是可行的,但 StreamBuilder 的发明是为了做同样的事情,不是吗?

4

3 回答 3

5

snapshot应该是一个元素列表,因此您可以length像这样访问列表:

body: StreamBuilder(
        stream: someStream,
        initialData: [],
        builder: (ctx, snapshot) {
          return ListView.separated(
            separatorBuilder: (context, index) => Divider(color: Colors.black),
            itemCount: snapshot.data.length,
            itemBuilder: (BuildContext ctx, int index) {
                final element = snapshot.data[index];

我建议将 也添加initialData到 StreamBuilder 中,这样您就不会在快照中使用空值。

希望能帮助到你

于 2019-11-13T14:44:47.197 回答
4

snapshot可以有不同的状态。

通常,您可以执行以下操作:

if (snapshot.hasError){
    //return error message
}

if (!snapshot.hasData){
    //return a loader
}

//else you have data
List<your items> = snapshot.data;
// do your thing with ListView.builder

要获得更多控制,您可以检查snapshot.connectionsStatewhich can be none, done, active, waiting.

您可以在此处找到有关 AsyncSnapshot 类的更多信息,并在此处获得快速教程

于 2019-11-13T14:45:14.173 回答
2

试试这个希望它对你有用

    body: StreamBuilder(
            stream: someStream,
            builder: (ctx, snapshot) {
              return ListView.separated(
                separatorBuilder: (context, index) => Divider(color: Colors.black),
                itemCount: snapshot.data.lenght,
                itemBuilder: (BuildContext ctx, int index) {
    final titre= snapshot.data[index].title ;  // for example

return ListTile ( title : Text(titre)) ;  
     //....
于 2019-11-13T14:46:15.870 回答