0

I need to store data on multiple levels: Test 1 > q1, q2, q3... > question: hello, answer: opt 2, opt 1: a, opt 2: b, opt 3: c, opt 4: d

So in actual terms I have multiples tests where in each test you have multiple questions and where each question has multiple options.

how can I add it to firestore and be able to load each test fast as at the moment it is delayed for long with the below code:

for (var i = 1; i < totalquestions + 1; i++) {
  await FirebaseFirestore.instance
      .collection("users")
      .doc(user!.uid)
      .collection('Test $no')
      .doc(i.toString())
      .set(
        Map<String, dynamic>.from(
          Provider.of<Question>(context, listen: false)
              .question[i]!,
        ),
      );
  await FirebaseFirestore.instance
      .collection("users")
      .doc(user.uid)
      .collection('Test $no')
      .doc(i.toString())
      .update(
    {
      'yourAns':
          Provider.of<Question>(context, listen: false)
              .answers[i]!
              .values
              .first
    },
  );
}
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • 2
    Nested fields in Firestore translate to nested `Map` objects in your Flutter code. Give it a try, and let us know if it doesn't work. ---- Consider whether the nested fields should be documents in a subcollection though. Pro's of that is that you can query them separately, load subsets of the data. The main cons of it is that you'll end up reading more documents. – Frank van Puffelen Jun 05 '23 at 20:37

1 Answers1

1

Posting this as a community wiki for everyone's visibility.

As mentioned by Frank, nested fields in Firestore translate to nested Map objects in Flutter. A thing to consider is whether the nested field should be documents in a subcollection. It will enable you to query them separately and load subsets of data, but you'll end up reading more documents. Here's a comprehensive answer on nested Maps in flutter.

Michael C
  • 308
  • 1
  • 6