Home > other >  How to save a list of objects in Firebase Firestore with flutter
How to save a list of objects in Firebase Firestore with flutter

Time:05-17

I want to store data into my Model (Task) class in firebase but not quite sure how I would do that with this model class.

class Task {
  String title;
  String owner;
  DateTime time;

  List<AssignedTask> assignedTask;

  Task(
      {required this.title,
      required this.owner,
      required this.time,
      required this.assignedTask});

  Map<String, dynamic> toJson() {
    return {
      'title': title,
      'owner': owner,
      'time': time,
      'assignedTask': assignedTask,
    };
  }

The AssignedTask Class

class AssignedTask {
  String name;
  String taskType;
  String employeeTask;
  bool? isComplete;
  String vehicle;

  AssignedTask(
      {required this.name,
      required this.taskType,
      required this.employeeTask,
      required this.isComplete,
      required this.vehicle});


      Map<String, dynamic> toJson() {
    return {
      'name': name,
      'taskType': taskType,
      'employeeTask': employeeTask,
      'isComplete': isComplete,
      'vehicle': vehicle,
    };
  }
}

List<Task> recentTasks = [
  Task(
    title: "18 Wheeler",
    owner: "Darth Vader",
    time: DateTime.parse("2020-06-06 12:30:00"),
    assignedTask: [
      AssignedTask(
          name: "John",
          taskType: "Mechinical",
          employeeTask: "Gear Box",
          isComplete: true,
          vehicle: "18 Wheeler"),
      AssignedTask(
          name: "Palpetine",
          taskType: "Trailer",
          employeeTask: "Faulty Steering System and Suspension",
          isComplete: false,
          vehicle: "18 Wheeler"),
      AssignedTask(
          name: "Windu",
          taskType: "Electronical",
          employeeTask: "Malfunctioning Wipers",
          isComplete: true,
          vehicle: "18 Wheeler"),
      AssignedTask(
          name: "Rex",
          taskType: "Mechinical",
          employeeTask: "Faulty Brakes",
          isComplete: false,
          vehicle: "18 Wheeler"),
    ],
  ),
]

This is how I had it saved as in a List, I want a way to put that into firestore. I mostly have an Issue where I have to save the List assignedTask; to firebase.

CodePudding user response:

The mistake you are making is, you are passing a list in toJson, but they also need to be converted to json. So your Task class should be like:

class Task {
  String title;
  String owner;
  DateTime time;

  List<AssignedTask> assignedTask;

  Task({
      required this.title,
      required this.owner,
      required this.time,
      required this.assignedTask});

  Map<String, dynamic> toJson() {
      return {
          'title': title,
          'owner': owner,
          'time': time,
          'assignedTask': assignedTask.map(a => a.toJson()).toList(),
      };
  };
}
  • Related