flutter 显示来自不同firestore集合的数据

dtcbnfnu  于 2023-02-09  发布在  Flutter
关注(0)|答案(2)|浏览(123)

我尝试显示firestore中两个不同集合的数据,我尝试嵌套两个streambuild,这样我就可以将数据显示为一个流,但是我一直收到错误bad state field doesnt exist with doc snapshot,我如何修复此错误,或者是否有其他更有效的方法可以用于显示一个类中两个不同集合的数据?
下面是我想显示的数据的屏幕截图:第一节第一节第一节第一节第一次

class OrderStream extends StatelessWidget {
  static const String route = "/Order";

  final CollectionReference meal =
      FirebaseFirestore.instance.collection("menu");
  final CollectionReference profile =
      FirebaseFirestore.instance.collection("users");

  OrderStream({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: StreamBuilder(
            stream: profile.snapshots(),
            builder: (context, AsyncSnapshot<QuerySnapshot> streamSnapshot) {
              return StreamBuilder(
                stream: meal.snapshots(),
                builder:
                    (context, AsyncSnapshot<QuerySnapshot> streamSnapshot) {
                  if (!streamSnapshot.hasData) {
                    return const SizedBox(
                      height: 250,
                      child: Center(
                        child: CircularProgressIndicator(),
                      ),
                    );
                  } else {
                    return ListView.builder(
                        itemCount: streamSnapshot.data!.docs.length,
                        itemBuilder: (context, index) {
                          final DocumentSnapshot documentSnapshot =
                              streamSnapshot.data!.docs[index];
                          return Column(
                             children: [
                            Text( documentSnapshot['price'],)
                            Text( documentSnapshot['name'],)
                             

                           ]
                              ),
                            ),
                      }
6vl6ewon

6vl6ewon1#

这可能是因为两个快照的名称相似。
检查这一点的最佳方法是重命名各个Streambuilder()的快照。

StreamBuilder(
            stream: profile.snapshots(),
            builder: (context, AsyncSnapshot<QuerySnapshot> profileStreamSnapshot) {
              return StreamBuilder(
                stream: meal.snapshots(),
                builder:
                    (context, AsyncSnapshot<QuerySnapshot> mealStreamSnapshot) {
                  if (!streamSnapshot.hasData) {
                    //modified (renamed snapshot variable) code here
                  }
ttcibm8c

ttcibm8c2#

您可以使用rxdart这样的库将这两个流合并为一个,该库具有combineLatest2方法,尽管您也可以使用StreamZip这样的库来获得相同的效果。
我使用了rxdart combineLatest2,如下所示:

import 'package:rxdart/rxdart.dart';//import ⇐

class MyHomePage extends StatelessWidget {
  final CollectionReference profile =
      FirebaseFirestore.instance.collection("users");
  final CollectionReference meal =
      FirebaseFirestore.instance.collection("menu");
  MyHomePage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: StreamBuilder(
          stream: Rx.combineLatest2(profile.snapshots(), meal.snapshots(),
              (QuerySnapshot profileSnapshot, QuerySnapshot mealSnapshot) {
            return [...profileSnapshot.docs, ...mealSnapshot.docs];
          }),
          builder: (context, AsyncSnapshot<List<DocumentSnapshot>> snapshot) {
            if (!snapshot.hasData) {
              return const SizedBox(
                height: 250,
                child: Center(
                  child: CircularProgressIndicator(),
                ),
              );
            } else {
              return ListView.builder(
                itemCount: snapshot.data!.length,
                itemBuilder: (context, index) {
                  final DocumentSnapshot documentSnapshot =
                      snapshot.data![index];
                  final Map<String, dynamic> data =
                      documentSnapshot.data() as Map<String, dynamic>;
                  if (data.containsKey("price") && data.containsKey("name")) {
                    return Column(
                      children: [Text(data["price"]), Text(data["name"])],
                    );
                  } else {
                    return Container();
                  }
                },
              );
            }
          }),
    );
  }
}

也可以按如下方式使用Stream.merge()

final Stream<QuerySnapshot> mealsStream = meal.snapshots();
final Stream<QuerySnapshot> profilesStream = profile.snapshots();
//.. All that Scaffold stuff
stream: Stream.merge([mealsStream, profilesStream]),

相关问题