Get the length of active sessions. (I am a student, I am learning)

import 'dart:convert';
import 'dart:math' as math;

import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:intl/intl.dart';
import 'package:timeago/timeago.dart' as timeago;
import '../../flutter_flow/lat_lng.dart';
import '../../flutter_flow/place.dart';
import '../../flutter_flow/uploaded_file.dart';
import '../../flutter_flow/custom_functions.dart';

String? newCustomFunction() {
  /// MODIFY CODE ONLY BELOW THIS LINE

  // show the lenght of all active sessions
// Sample data
  final List<Map<String, dynamic>> sessions = [
    {
      'id': 1,
      'start_time': '2022-01-01T10:00:00Z',
      'end_time': '2022-01-01T12:00:00Z',
    },
    {
      'id': 2,
      'start_time': '2022-01-02T14:00:00Z',
      'end_time': '2022-01-02T16:00:00Z',
    },
    {
      'id': 3,
      'start_time': '2022-01-03T09:00:00Z',
      'end_time': null,
    },
  ];

  // Calculate the length of all active sessions
  final now = DateTime.now().toUtc();
  final activeSessions = sessions.where((session) =>
      DateTime.parse(session['start_time']).isBefore(now) &&
      (session['end_time'] == null ||
          DateTime.parse(session['end_time']).isAfter(now)));
  final totalLength = activeSessions.fold(Duration(), (prev, session) {
    final start = DateTime.parse(session['start_time']).toUtc();
    final end = session['end_time'] == null
        ? now
        : DateTime.parse(session['end_time']).toUtc();
    return prev + end.difference(start);
  });

  // Format the duration as a string
  final formatter = DateFormat('HH:mm:ss');
  final lengthString = formatter.format(DateTime(0).add(totalLength));

  // Return the length of all active sessions
  return 'The length of all active sessions is $lengthString.';

  /// MODIFY CODE ONLY ABOVE THIS LINE
}
6
2 replies