Flutter:如何将 StreamBuilder 与 ListView.separated 结合使用

Flutter: How to use StreamBuilder with ListView.separated

我想要一个包含来自流的项目的 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 的发明就是为了做同样的事情,不是吗?

您的 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,这样您就不会在快照中使用空值。

希望对您有所帮助

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.connectionsState,它可以是 nonedoneactivewaiting.

您可以找到更多 here for the AsyncSnapshot class and here for a quick tutorial

试试这个希望对你有用

    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)) ;  
     //....