Home > OS >  How do I set up a nested field in a Cloud Firestore database using JSONserializable in flutter
How do I set up a nested field in a Cloud Firestore database using JSONserializable in flutter

Time:09-08

I have set up two of the Collections in My Cloud Firestore database in Flutter using JSONSerializable. This is shown below

models.dart

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:json_annotation/json_annotation.dart';
part 'models.g.dart';

enum RecordType {
  weightAndReps,
  repsOnly,
  time,
  timeAndWeight,
  distance,
}

@JsonSerializable()
class User {
  final String id;
  final String username;
  final String name;
  final String email;
  final String password;
  final String image;
  final bool isAdmin;

  User(
      {this.id = '',
      this.username = '',
      this.name = '',
      this.email = '',
      this.password = '',
      this.image = '',
      this.isAdmin = false});

  factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);
  Map<String, dynamic> toJson() => _$UserToJson(this);
}

@JsonSerializable()
class Exercise {
  final String id;
  final String name;
  final String description;
  final String image;
  final RecordType recordType;
  final String primaryMuscleGroup;
  final List<String> secondaryMuscleGroup;

  Exercise(
      {this.id = '',
      this.name = '',
      this.description = '',
      this.image = '',
      this.recordType = RecordType.weightAndReps,
      this.primaryMuscleGroup = '',
      this.secondaryMuscleGroup = const []});

  factory Exercise.fromJson(Map<String, dynamic> json) =>
      _$ExerciseFromJson(json);
  Map<String, dynamic> toJson() => _$ExerciseToJson(this);
}

However, I am having problems with the Workout Collection due to the number of nested fields and the fact that the Map datatypes in use have more than two elements which I cannot utilise in dart. I am fairly new to this and cannot find much online on how to do this. The collection in question is shown in the image below.

enter image description here

Any help would be greatly appreciated

CodePudding user response:

Your workout collection can be represented by the below model.

class Workout {
  final int durationInWeeks;
  final String image;
  final String name;
  final List<Session> sessions; // Session defined below

  Workout({
    required this.durationInWeeks,
    required this.image,
    required this.name,
    required this.sessions,
  });

  factory Workout.fromJson(Map<String, dynamic> json) =>
      _$WorkoutFromJson(json);
  Map<String, dynamic> toJson() => _$WorkoutToJson(this);
}

class Session {
  final String description;
  final List<Exercise> exercise;
  final int weeklySessions;

  Session({
    required this.description,
    required this.exercise,
    required this.weeklySessions,
  });

  factory Session.fromJson(Map<String, dynamic> json) =>
      _$SessionFromJson(json);
  Map<String, dynamic> toJson() => _$SessionToJson(this);
}
  • Related