I’m getting an error with when retrieving data from my Cloud Firestore database

Issue

This Content is from Stack Overflow. Question asked by Leonard

Hi keep getting an error retrieving data from my Cloud Firestore database. I believe it has something to do with my models.dart file which uses JSONSerializable.

Firestore document
document from the workout collection from the Firestore database

models.dart

@JsonSerializable()
class Exercise {
  final String id;
  final String name;
  final String equipment;
  final String image;
  final String muscleGroup;

  Exercise(
      {this.id = '',
      this.name = '',
      this.equipment = '',
      this.image = '',
      this.muscleGroup = ''});

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

@JsonSerializable()
class Workout {
  final String id;
  final String name;
  final String description;
  final String image;
  final int numberOfSessions;
  final int durationInWeeks;
  final List<Session> sessions;

  Workout(
      {this.id = '',
      this.name = '',
      this.description = '',
      this.image = 'default.png',
      this.numberOfSessions = 0,
      this.durationInWeeks = 0,
      this.sessions = const []});

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

@JsonSerializable()
class Session {
  final String name;
  final String description;
  final List<ExerciseElement> exercises;

  Session({this.name = '', this.description = '', this.exercises = const []});

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

@JsonSerializable()
class ExerciseElement {
  final int id;
  final Exercise? exercise;
  final List<int> targetReps;
  final List<int> targetSets;
  final List<int> sets;
  final List<int> reps;
  final List<int> weight;
  final int rest;

  ExerciseElement(
      {this.id = 0,
      this.exercise,
      this.targetReps = const [],
      this.targetSets = const [],
      this.sets = const [],
      this.reps = const [],
      this.weight = const [],
      this.rest = 0});

  factory ExerciseElement.fromJson(Map<String, dynamic> json) =>
      _$ExerciseElementFromJson(json);
  Map<String, dynamic> toJson() => _$ExerciseElementToJson(this);
}

The error is that every time it runs the snapshot.hasError is called. It occurs in activity.dart

activity.dart

// import 'package:barbellplus/models/workout_days.dart';
import 'package:barbellplus/services/firestore.dart';
import 'package:barbellplus/services/models.dart';
import 'package:flutter/material.dart';

class RecentActivities extends StatelessWidget {
  const RecentActivities({super.key});

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<Workout>(
        future: FirestoreService().getWorkout('upper-lower-4-day'),
        builder: (context, snapshot) {
          if (snapshot.hasError) {
            return const Text('Something went wrong');
          }

          if (snapshot.connectionState == ConnectionState.waiting) {
            return const Center(
              child: CircularProgressIndicator(),
            );
          }
          return Expanded(
            child: Padding(
              padding: const EdgeInsets.symmetric(vertical: 20, horizontal: 30),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  const Text('Recent Activities',
                      style: TextStyle(
                        color: Colors.black,
                        fontWeight: FontWeight.bold,
                        fontSize: 18,
                      )),
                  Expanded(
                    child: ListView.builder(
                      itemCount: snapshot.data!.numberOfSessions,
                      itemBuilder: (context, index) => ActivityItem(
                        session: snapshot.data!.sessions[index],
                      ),
                    ),
                  ),
                ],
              ),
            ),
          );
        });
  }
}

class ActivityItem extends StatelessWidget {
  final Session session;

  // ignore: prefer_const_constructors_in_immutables
  ActivityItem({super.key, required this.session});

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        Navigator.pushNamed(context, '/activity');
      },
      child: Container(
          margin: const EdgeInsets.symmetric(vertical: 5),
          height: 50,
          decoration: BoxDecoration(
            border: Border.all(
              color: Colors.white,
            ),
            borderRadius: BorderRadius.circular(10),
          ),
          child: Row(
            children: [
              const SizedBox(width: 10),
              Container(
                decoration: const BoxDecoration(
                    shape: BoxShape.circle, color: Color(0xffcff2ff)),
                height: 35,
                width: 35,
                child: Container(
                  padding: const EdgeInsets.all(4),
                  decoration: const BoxDecoration(
                    shape: BoxShape.circle,
                    image: DecorationImage(
                      image: AssetImage('assets/images/bodybuilder-1.jpg'),
                      fit: BoxFit.fill,
                    ),
                  ),
                ),
              ),
              const SizedBox(width: 20),
              Text(session.name,
                  style: const TextStyle(
                    fontWeight: FontWeight.w900,
                    fontSize: 12,
                  )),
              const Expanded(child: SizedBox()),
              const Icon(Icons.timer, size: 12),
              const SizedBox(width: 5),
              Text(
                session.name,
                style:
                    const TextStyle(fontSize: 10, fontWeight: FontWeight.w300),
              ),
              const SizedBox(width: 10),
              const Icon(Icons.wb_sunny_outlined, size: 12),
              const SizedBox(width: 5),
              const Text(
                'test',
                style: TextStyle(fontSize: 10, fontWeight: FontWeight.w300),
              ),
            ],
          )),
    );
  }
}

Please let me know if any other information is needed. Any help would be greatly appreciated.



Solution

This question is not yet answered, be the first one who answer using the comment. Later the confirmed answer will be published as the solution.

This Question and Answer are collected from stackoverflow and tested by JTuto community, is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?