'Using a Stream builder inside a Future builder (Flutter with Firestore)

I want to use a stream to get data from a Firestore document, but getting the stream involves reading from Firestore first. This means that it is async, and therefore returns a Future<Stream>:

Future<Stream<WeekData>?> thisWeekStream(DateTime weekStartDate) async {
  // A few steps here involving reading from Firestore to find the appropriate document
  // (i.e. async functions)

  return weekDataCollection.doc(doc.id).snapshots().map((snapshot) =>
    WeekData.fromJson(doc.id, snapshot.data() as Map<String, Object?>));
  }
}

So for my screen, I am using a FutureBuilder with a StreamBuilder inside it:

FutureBuilder<Stream<WeekData>?>(
        // Firstly, get the Future of Stream<WeekData>
        future: _weekDataDatabase.thisWeekStream(DateTime.now().getWeekStart()),
        builder: (context, snapshot) {
          if (snapshot.hasError) {
            return const Text('Error in FutureBuilder');
          } else if (snapshot.connectionState == ConnectionState.waiting) {
            return const LoadingWidget(); // Loading the Future
          } else if (snapshot.hasData) {
            // Once Future is completed and returns Stream<WeekData>, build UI using stream
            return StreamBuilder<WeekData>(builder: (context, snapshot) {
              if (snapshot.hasData) {
                WeekData weekData = snapshot.data!;
                return Column(
                  children: [
                    Text(weekData.weekStartDate.toString()),
                    Text(weekData.nSessionsList.toString()),
                  ],
                );
              } else if (snapshot.connectionState == ConnectionState.waiting) {
                return const LoadingWidget(); // Loading the Stream
              } else {
                return const Text('Error in stream');
              }
            });
          } else {
            return const LoadingWidget();
          }
        },
      ),

But it's not working: on the screen, I get the text widget "Error in stream" and when I looked inside in the debug console, ConnectionState for the stream appeared to be ConnectionState.none. I can't figure out why the stream is returning nothing.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source