Flutter snapshots from one StreamBuilder is showing in another StreamBuilder

Issue

I have two collections (‘stream1’, ‘stream2’) from firestore and I want them to render to the screen using a StreamBuilder and a ListView. I have 2 buttons that I use to switch between ListViews. But I’m getting an error that says Bad state: field does not exist within the DocumentSnapshotPlatform when switching back and forth within the ListViews. Somehow the snapshot from one StreamBuilder is present in the second StreamBuilder and causing the error message since the fields are different from both collections. Here is the code:

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'),
          ),
        )
      ],
    ),
  ),
);
}
}

Solution

Solved my problem by separating each StreamBuilder into its own build method.

Answered By – Sev

Answer Checked By – Jay B. (FlutterFixes Admin)

Leave a Reply

Your email address will not be published.