0

I created a function fetch tasks to access the collection timestamps and retrieve its documents and place them into a list but for some reason the list always comes out empty. To replicate the error you would need to create a firebase database of the format User --> (doc) --> Tasks --> (doc) --> Timestamp --> (date) --> StartStop --> (doc) --> (field called either start or stop with a time value). Here is the code of the function:

void _fetchTasks() async {
    try {
      final currentUser = FirebaseAuth.instance.currentUser;
      if (currentUser != null) {
        final querySnapshot = await FirebaseFirestore.instance
            .collection('Users')
            .doc(currentUser.uid)
            .collection('Tasks')
            .where('status', isEqualTo: 'active') // Filter by status 'active'
            .get();

        List<TaskData> data = [];

        for (var doc in querySnapshot.docs) {
          final taskData = doc.data();
          String taskName = taskData['name'] ?? 'Unknown';
          int color = taskData['color'] ?? Colors.grey.value;

          final timestampsSnapshot = await FirebaseFirestore.instance
              .collection('Users')
              .doc(currentUser.uid)
              .collection('Tasks')
              .doc(doc.id)
              .collection('Timestamps')
              .get();

          print('Timestamps snapshot for task: $taskName - ${timestampsSnapshot.docs.length} documents found');

          for (var timestampDoc in timestampsSnapshot.docs) {
            print('Processing timestamp document ID: ${timestampDoc.id}');
            CollectionReference startStopRef = FirebaseFirestore.instance
                .collection('Users')
                .doc(currentUser.uid)
                .collection('Tasks')
                .doc(doc.id)
                .collection('Timestamps')
                .doc(timestampDoc.id)
                .collection('StartStop');

            print('StartStop reference: $startStopRef');
            QuerySnapshot startStopSnapshot = await startStopRef.get();

            print('StartStop snapshot: ${startStopSnapshot.docs.length} documents found');

            List<DateTime> startStopTimes = [];

            for (var startStopDoc in startStopSnapshot.docs) {
              var startStopData = startStopDoc.data() as Map<String, dynamic>;

              print('Start/Stop data: $startStopData');

              if (startStopData.containsKey('start')) {
                startStopTimes.add(_parseTimeString(startStopData['start'], timestampDoc.id));
              } else if (startStopData.containsKey('stop')) {
                startStopTimes.add(_parseTimeString(startStopData['stop'], timestampDoc.id));
              }
            }

            startStopTimes.sort();
            print('Sorted startStopTimes: $startStopTimes');

            for (int i = 0; i < startStopTimes.length - 1; i += 2) {
              DateTime start = startStopTimes[i];
              DateTime stop = startStopTimes[i + 1];

              int duration = stop.difference(start).inMinutes;
              data.add(TaskData(taskName, color, duration, timestampDoc.id));
              print('TaskData added: $taskName, $duration minutes on ${timestampDoc.id}');
            }
          }
        }

        setState(() {
          _data = data;
          _generateData(_data);
        });

        print('Data fetched successfully. Data length: ${data.length}');
        if (_data.isNotEmpty) {
          print('Sample data: ${_data[0].name}, ${_data[0].duration} minutes on ${_data[0].day}');
        }
      } else {
        print('No user is currently signed in.');
      }
    } catch (error) {
      print('Error fetching tasks: $error');
    }
  }

  DateTime _parseTimeString(String timeString, String date) {
    try {
      final dateTimeString = '$date $timeString';
      return DateTime.parse(dateTimeString);
    } catch (e) {
      print('Error parsing time string: $timeString for date: $date. Error: $e');
      return DateTime.now();  // Return current time to avoid null issues
    }
  }

I tried modifying my firebase database structure but it is the same used in the function so I don't see what could be the problem.

3
  • 1
    Welcome to SO! Please note that "it isnt behaving as expected" isn't a proper description of the issue. Please edit your question to include the exact problem you are receiving. Is there an error in the console? what does your db structure look like?
    – MendelG
    Commented Jul 7 at 9:53
  • I'm not sure I understand. What exactly in this code doesn't work the way you expect? Tell us what is wrong with shared code. Do you have any errors? Please edit your question and add your database structure as a screenshot. Please also respond using @AlexMamo
    – Alex Mamo
    Commented Jul 7 at 10:16
  • @AlexMamo I corrected the question to include details of what wasnt working as expected though I mentioned it in the title. The goal was to fetch the timestamp documents from my firebase database as I explained.
    – Luis Silva
    Commented Jul 9 at 16:20

0