How to store list dynamic field data to existing collection on Firebase using Flutter

Viewed 354

I have create some dynamic fields for user to submit their exam which are subject and grades. I know how to loop the data and store it in an array and display it as a JSON string format but I don't know how to store the data to an existing collection on Firebase.

Please guide me to fix this problem.

Here is the function code :

saveSPMResultToFirebase() async {
  User? currentUser = FirebaseAuth.instance.currentUser;
  List entries = [];
  
  for (int i = 0; i < forms.length; i++) {
    final subjectId = i.toString();
    final subjectName = nameTECs[i].text;
    final subjectGrade = gradeTECs[i];
    entries.add(SPMModel(
      subjectId: subjectId,
      subjectName: subjectName,
      subjectGrade: subjectGrade
    ));
  }

  await FirebaseFirestore.instance
        .collection("users")
        .doc(currentUser!.uid)
        .update({'spmResult': entries.toString()});

  //debugPrint(entries.toString());
}

Here is the model I used to store the data as json string format

class SPMModel {
  String? subjectId;
  String? subjectName;
  String? subjectGrade;

  SPMModel({this.subjectId, this.subjectName, this.subjectGrade});

  //receive data from database
  factory SPMModel.fromJson(map) {
    return SPMModel(
      subjectId: map['subjectId'],
      subjectName: map['subjectName'],
      subjectGrade: map['subjectGrade'],
    );
  }

  @override
  String toString() {
    return '{subjectId: $subjectId, subjectName: $subjectName, subjectGrade: $subjectGrade}';
  }
}

Here is the model of the existing collection

class UserProfileModel {
  String? uid;
  String? email;
  String? fullName;
  String? nric;
  String? age;
  String? gender;
  String? ethnicity;
  String? religion;
  String? address;
  String? state;
  String? country;
  String? phone;
  String? parentName;
  String? parentPhone;
  String? spmResult;

  UserProfileModel({
    this.uid,
    this.email,
    this.fullName,
    this.nric,
    this.age,
    this.gender,
    this.ethnicity,
    this.religion,
    this.address,
    this.state,
    this.country,
    this.phone,
    this.parentName,
    this.parentPhone,
    this.spmResult,
  });

  //receive data from database
  factory UserProfileModel.fromMap(map) {
    return UserProfileModel(
      uid: map['uid'],
      email: map['email'],
      fullName: map['fullName'],
      nric: map['nric'],
      age: map['age'],
      gender: map['gender'],
      ethnicity: map['ethnicity'],
      religion: map['religion'],
      address: map['address'],
      state: map['state'],
      country: map['country'],
      phone: map['phone'],
      parentName: map['parentName'],
      parentPhone: map['parentPhone'],
      spmResult: map['spmResult']
    );
  }

  //send data to database
  Map<String, dynamic> toMap() {
    return {
      'uid': uid,
      'email': email,
      'fullName': fullName,
      'nric': nric,
      'age': age,
      'gender': gender,
      'ethnicity': ethnicity,
      'religion': religion,
      'address': address,
      'state': state,
      'country': country,
      'phone': phone,
      'parentName': parentName,
      'parentPhone': parentPhone,
      'spmResult': spmResult
    };
  }
}

For now this is the progress that I made. It successfully stored to Firebase but as a string. Not as a sub data of the existing collection. Output From Cloud Firestore

1 Answers

I have solved my own problem.

Dynamic field model

class SPMModel {
  String? subjectName;
  String? subjectGrade;

  SPMModel(this.subjectName, this.subjectGrade);

  Map<String, dynamic> toMap() => {
    "subjectName": subjectName,
    "subjectGrade": subjectGrade,
  };
}

User Model (I created a list dynamic field array on existing collection model)

class UserProfileModel {
  List<dynamic> spmResult = [];
    
  //send data to database
  Map<String, dynamic> toMap() {
    return {
      'spmResult': spmResult
    };
  }
}

submit Function (store to firebase)

saveSPMResultToFirebase() async {
  User? currentUser = FirebaseAuth.instance.currentUser;  
  SPMModel spmModel;
  for (int i = 0; i < forms.length; i++) {
    final subjectName = nameTECs[i].text;
    final subjectGrade = gradeTECs[i];

    spmModel = SPMModel(subjectName, subjectGrade);

    await FirebaseFirestore.instance
    .collection("users")
    .doc(currentUser!.uid)
    .update({
      "spmResult": FieldValue.arrayUnion([spmModel.toMap()])
    });
  }
}

Output Firebase

Related