I am trying to fetch data from various collections in Firebase for a flutter app. However, I've noticed that as the number of documents in my collections increase, the longer it takes for it to display in my app on an emulator using Android Studio. Specifically, for the collection with 1 doc, it loads instantly, for the collection with 2 docs, it takes a little longer, and for my collection with 5 docs, it doesn't load at all. How can I solve this problem? All docs have the same number of fields and I am mapping the same function on all collections to access and display their data.
This is the code I use to fetch the data, and I call this class in my main.dart file. This current code does have a rangeError currently since I'm not checking whether the currentIndex is within the bounds, but I believe the issues are unrelated since I cannot get the first question to display in case the subject is 'biology', which is the collection with 5 docs.
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_core/firebase_core.dart';
import './questions.dart';
class QuizPage extends StatefulWidget {
final String subjectHolder;
const QuizPage(this.subjectHolder, {Key? key}) : super(key: key);
@override
State<QuizPage> createState() => _QuizPageState();
}
class _QuizPageState extends State<QuizPage> {
String subject = 'biology';
@override
void initState(){
subject = widget.subjectHolder;
super.initState();
}
Stream<List<Question>> readQuestions() =>
FirebaseFirestore.instance.collection(subject).snapshots()
.map((snapshot) => snapshot.docs.map((doc) => Question.fromJson(doc.data())).toList());
var currentIndex = 0;
@override
Widget build(BuildContext context) {
return Scaffold(
body: StreamBuilder<List<Question>>(
stream: readQuestions(),
builder: (context, snapshot) {
if (snapshot.hasData) {
final questions = snapshot.data!;
return Center(
child: Column(children: [
Text("${questions[currentIndex].question}"),
ElevatedButton(onPressed: () {
setState(() {
currentIndex +=1;
});
},
child: Text("${questions[currentIndex].option_a}")),
ElevatedButton(onPressed: () {
setState(() {
currentIndex +=1;
});
},
child: Text("${questions[currentIndex].option_b}")),
ElevatedButton(onPressed: () {
setState(() {
currentIndex +=1;
});
},
child: Text("${questions[currentIndex].option_c}")),
]
),
);
}
else {
return Center(child: CircularProgressIndicator());
}
}),
);
}
}