0

我有两个来自 firestore 的集合('stream1'、'stream2'),我希望它们使用 StreamBuilder 和 ListView 呈现到屏幕上。我有 2 个用于在 ListView 之间切换的按钮。但是我收到一个错误,说状态不好:在 ListViews 中来回切换时,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'),
          ),
        )
      ],
    ),
  ),
);
}
}
4

1 回答 1

1

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

于 2021-10-22T11:43:06.463 回答