【问题标题】:Flutter snapshots from one StreamBuilder is showing in another StreamBuilder来自一个 StreamBuilder 的 Flutter 快照显示在另一个 StreamBuilder 中
【发布时间】:2021-12-06 22:12:50
【问题描述】:

我有两个来自 firestore 的集合('stream1'、'stream2'),我希望它们使用 StreamBuilder 和 ListView 呈现到屏幕上。我有 2 个用于在 ListView 之间切换的按钮。但是当在 ListViews 中来回切换时,我收到一条错误消息,提示 Bad state: field does not exist within DocumentSnapshotPlatform。不知何故,来自一个 StreamBuilder 的快照存在于第二个 StreamBuilder 中,并导致错误消息,因为字段与两个集合不同。代码如下:

import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:stream_bug/controller.dart';
import 'package:get/get.dart';

class HomePage extends StatelessWidget {
 const HomePage({Key? key}) : super(key: key);

 static final Controller _controller = Get.put(Controller());

_buildList(String collectionName) {
return StreamBuilder<QuerySnapshot>(
  stream: FirebaseFirestore.instance.collection(collectionName).snapshots(),
  builder: (context, snapshot) {
    print(snapshot.data!.docs[0].data()); // added a print statement here to show that the snapshot is not from 'stream1' but 'stream2' and vice versa.
    if (snapshot.hasError) {
      return Center(
        child: Text('error'),
      );
    }
    if (!snapshot.hasData) {
      return Center(child: CircularProgressIndicator());
    }

    return Container(
      height: 300,
      child: ListView.builder(
        itemCount: snapshot.data!.docs.length,
        itemBuilder: ((context, index) {
          if (collectionName == 'stream1') {

            // this line is where the error shows up
            return ListTile(
              title: Text(snapshot.data!.docs[index]['1'].toString()),
            );
          } else if(collectionName == 'stream2'){
            // this line is where the error shows up as well
            return ListTile(
              title: Text(snapshot.data!.docs[index]['a'].toString()),
            );
          }
        }),
      ),
    );
  },
);
}

@override
Widget build(BuildContext context) {
return Scaffold(
  body: Center(
    child: Column(
      children: [
        SizedBox(height: 100),
        ElevatedButton(
            onPressed: () {
              _controller.updateStream(0);
            },
            child: Text('Stream 1')),
        ElevatedButton(
            onPressed: () {
              _controller.updateStream(1);
            },
            child: Text('Stream 2')),
        Obx(
          () => Container(
            child: _controller.currentStream.value == 0
                ? _buildList('stream1')
                : _buildList('stream2'),
          ),
        )
      ],
    ),
  ),
);
}
}

【问题讨论】:

标签: flutter google-cloud-firestore flutter-streambuilder


【解决方案1】:

通过将每个 StreamBuilder 分成自己的构建方法来解决我的问题。

【讨论】:

    猜你喜欢
    • 2021-10-21
    • 2023-03-29
    • 2021-07-01
    • 2023-02-11
    • 2020-07-19
    • 2020-10-26
    • 2018-04-30
    • 1970-01-01
    • 2021-07-26
    相关资源
    最近更新 更多