Flutter:如何将 StreamBuilder 与 ListView.separated 一起使用

pap*_*nik 1 listview stream dart flutter stream-builder

我想要一个包含来自 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) {
...
Run Code Online (Sandbox Code Playgroud)

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

nic*_*nli 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];
Run Code Online (Sandbox Code Playgroud)

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

希望能帮助到你


mag*_*n94 5

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
Run Code Online (Sandbox Code Playgroud)

要进行更多控制,您可以检查哪些snapshot.connectionsState可以是none, done, active, waiting

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