Home > Back-end >  Dynamically Calculate Time using Loops in Dart
Dynamically Calculate Time using Loops in Dart

Time:09-21

I need to create 96 Map objects in a List with the following key-value pairs

{
    'id': 1, 
    'time': '00:00-00:15', 
    'slotNumber': '01', 
    'clicked': false
}

Although this is something that is easily achievable using loops, the main complication starts when it comes to generating the time range. The time key in every object needs to be at an interval of 15 minutes each and should be in a 24-hour format. For example, the next few time ranges need to be 00:15-00:30, 00:30-00:45, 00:45-01:00, and so on. I tried hard to look a for a package that would answer all my prayers but couldn't find any.

The final output needs to look something like this:

var kSlots = [
  {'id': 1, 'time': '00:00-00:15', 'slotNumber': '01', 'clicked': false},
  {'id': 2, 'time': '00:15-00:30', 'slotNumber': '02', 'clicked': false},
  {'id': 3, 'time': '00:45-01:00', 'slotNumber': '03', 'clicked': false},
  {'id': 4, 'time': '01:00-01:15', 'slotNumber': '04', 'clicked': false},
  {'id': 5, 'time': '01:15-01:30', 'slotNumber': '05', 'clicked': false},
  {'id': 6, 'time': '01:30-01:45', 'slotNumber': '06', 'clicked': false},
  {'id': 7, 'time': '01:45-02:00', 'slotNumber': '07', 'clicked': false},
  {'id': 8, 'time': '02:00-02:15', 'slotNumber': '08', 'clicked': false}]

CodePudding user response:

Loop over an index and use the index as a multiplier for a Duration of 15 minutes.

You then either can add that multiplied Duration to a DateTime representing midnight (if your time ranges represent points in time) or format those Durations directly (if they represent durations).

I assuming that your times represent points in time:

import 'package:intl/intl.dart';

String getTimeRange(int i) {
  var midnight = DateTime.utc(2022, 1, 1);
  const interval = Duration(minutes: 15);
  var start = midnight.add(interval * i);
  var end = start.add(interval);
  var formatTime = DateFormat('HH:mm').format;
  return '${formatTime(start)}-${formatTime(end)}';
  
}

void main() {
  var slots = [
    for (var i = 0; i < 8; i  = 1)
    <String, dynamic>{
      'id': i   1,
      'time': getTimeRange(i),
      'slotNumber': '${i   1}'.padLeft(2, '0'),
      'clicked': false,
    },
  ];
  
  slots.forEach(print);
}

CodePudding user response:

You can set use the DateTime class instead of String and manipulate it as you desire: https://api.flutter.dev/flutter/dart-core/DateTime-class.html

  • Related