Flutter Getx: Adding List of data to Firestore as an array

Viewed 42

I have two model classes, StudentRecords, and Records. The StudentRecords class has a variable Records as a Lists. I have a Firestore collection named studentRecords in which I want to add data from StudentRecords class, and Records should be an array inside that collection. I am using Getx as my state management. Let me post the model classes first.

class RecordModel extends Equatable {
  final String? juz;
  final String? page;
  final String? surah;
  final String? ayat;
  final double? grade;

  const RecordModel({
    this.juz,
    this.page,
    this.surah,
    this.ayat,
    this.grade,
  });  

Next is StudentRecords model class.

class StudentRecords extends Equatable {
  String? studentId;
  double? avgGrade;
  Timestamp? createdOn;
  String? createdBy;
  String? createdById;
  List<RecordModel>? recordsModel;
  DocumentReference? documentReference;

  StudentRecords({
    required this.studentId,
    required this.avgGrade,
    required this.createdOn,
    required this.createdBy,
    required this.createdById,
    required this.recordsModel,
  });

  @override
  List<Object?> get props =>
      [studentId, avgGrade, createdOn, createdBy, createdById, recordsModel];

  StudentRecords copyWith({
    String? studentId,
    double? avgGrade,
    Timestamp? createdOn,
    String? createdBy,
    String? createdById,
    List<RecordModel>? murajaatRecords,
  }) {
    return StudentRecords(
      studentId: studentId ?? this.studentId,
      avgGrade: avgGrade ?? this.avgGrade,
      createdOn: createdOn ?? this.createdOn,
      createdBy: createdBy ?? this.createdBy,
      createdById: createdById ?? this.createdById,
      recordsModel: murajaatRecords ?? recordsModel,
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'studentId': studentId,
      'avgGrade': avgGrade,
      'createdOn': createdOn,
      'createdBy': createdBy,
      'createdById': createdById,
      'murajaatRecords':
          List<RecordModel>.from(recordsModel!.map((e) => e.toJson())),
    };
  }  

Next is my firebase firestore function to add data to the collection.

Future<void> addStudentRecord(
      {required double? avgGrade,
      Timestamp? createdOn,
      String? createdBy,
      required List<RecordModel> recordsModel}) async {
    // getting path to the studentRecords
    DocumentReference docRef = _firebaseFirestore
        .collection(FirestoreConstants.pathUserCollection)
        .doc(_firebaseAuth.currentUser!.uid)
        .collection('studentRecords')
        .doc();
    // getting name of the signed in user
    final docSnapshot =
        await _collectionReference.doc(_firebaseAuth.currentUser!.uid).get();
    if (docSnapshot.exists) {
      Map<String, dynamic>? data = docSnapshot.data();
      var createdBy = data?[FirestoreConstants.name];

      StudentRecords StudentRecords = StudentRecords(
        studentId: documentReference!.id,
        avgGrade: avgGrade,
        createdOn: Timestamp.now(),
        createdBy: createdBy,
        createdById: _firebaseAuth.currentUser!.uid,
        recordsModel: recordsModel,
      );

      FirebaseFirestore.instance.runTransaction((transaction) async {
        transaction.set(docRef, studentRecords.toJson());
      });
    }
  }  

Next, is my getx function in the controller class.

final recordModel = <RecordModel>[].obs;

void addStudentRecord() async {
    try {
      await _firestoreFunctions
          .addStudentRecord(
              avgGrade: averageGrade.value, recordsModel: recordModel)
          .then((value) => Get.snackbar('Success', 'Record Added Successfully',
              snackPosition: SnackPosition.BOTTOM));
    } on FirebaseException catch (e) {
      if (kDebugMode) {
        print("Firebase Exception: $e");
      }
    }
  }. 

What I am looking for is something like the sample given in the image below (ignore the array field name).
enter image description here.

I am missing something very vital here, which is why the data is not getting added to the database. I am unable to figure it out. Please help. If any further information is needed, let me know. Thanks.

0 Answers
Related