Jason Simard
Jason Simard

Reputation: 133

Table Calendar stacking events for specific date - Flutter

I am using Flutter, firestore with table calendar.

Here is my code, currently working but with a small glitch

              //Initialize Events
              List<Event> eventList = List<Event>();
              //Get events and add them to the list.
              eventsSnapshot.data.documents.forEach((doc) {
                Timestamp _eventDateStart = doc.data['eventDateStart'];
                Timestamp _eventDateFinish = doc.data['eventDateFinish'];
                Event _thisEvent = Event('test',
                      doc.data['eventName'],
                      doc.data['eventPrice'],
                      doc.data['eventDescription'],
                      _eventDateStart.toDate(),
                      _eventDateFinish.toDate());
                print('Event added : ${_thisEvent.eventName.toString()}');
                eventList.add(_thisEvent);
               });
               
              _events = convertToMap(eventList);

here is my converToMap

class Event {
  final String id;
  final String eventName;
  final double eventPrice;
  final String eventDescription;
  final DateTime eventDateStart;
  final DateTime eventDateFinish;

  Event(this.id, this.eventName, this.eventPrice,this.eventDescription, this.eventDateStart, this.eventDateFinish);
}

//method to change calendar item to Map<DateTime,List>
Map<DateTime, List<Event>> convertToMap(List<Event> item) {
  Map<DateTime, List<Event>> result;

  for (int i = 0; i < item.length; i++) {
    Event data = item[i];
    //get the date and convert it to a DateTime variable
    DateTime currentDate = data.eventDateStart;
    List<Event> events = [];
    //add the event name to the the eventNames list for the current date.
    //search for another event with the same date and populate the eventNames List.
    for (int j = 0; j < item.length; j++) {
      //create temp calendarItemData object.
      Event temp = item[j];
      //establish that the temp date is equal to the current date
      if (data.eventDateStart == temp.eventDateStart) {
        //add the event name to the event List.
        events.add(temp);
      } //else continue
    }

    //add the date and the event to the map if the date is not contained in the map
    if (result == null) {
      result = {currentDate: events};
    } else {

      result[currentDate] = events;
    }
  }
  print(result);
  return result;
}

The result of the print is pretty this.

I/flutter ( 1655): Event added : deuxio I/flutter ( 1655): Event added : PremierVraiTest I/flutter ( 1655): Event added : Test I/flutter ( 1655): {2020-09-17 13:00:00.000: [Instance of 'Event'], 2020-09-17 12:00:00.000: [Instance of 'Event'], 2020-09-18 12:00:00.000: [Instance of 'Event']}

The problem now: When I check my calendar I see 1 event of the 17 and 1 event for the 18. The 17 event is the one with 13:00. I don't see the second event.

Upvotes: 0

Views: 4269

Answers (1)

chunhunghan
chunhunghan

Reputation: 54397

You can copy paste run full code below
Reason 2020-09-17 13:00:00 != 2020-09-17 12:00:00, when use Map result[currentDate] you won't get 2 Events
You can use only DateTime(year, month, day)
code snippet

  DateTime currentDate = DateTime(data.eventDateStart.year,
      data.eventDateStart.month, data.eventDateStart.day);

  ...
  for (int j = 0; j < item.length; j++) {
    ...
    if (DateTime(data.eventDateStart.year, data.eventDateStart.month,
            data.eventDateStart.day) ==
        DateTime(temp.eventDateStart.year, temp.eventDateStart.month,
            temp.eventDateStart.day)) {

output

I/flutter (21975): {2020-09-17 00:00:00.000: [Instance of 'Event', Instance of 'Event']}
I/flutter (21975): 2

full code

import 'package:flutter/material.dart';

class Event {
  final String id;
  final String eventName;
  final double eventPrice;
  final String eventDescription;
  final DateTime eventDateStart;
  final DateTime eventDateFinish;

  Event(this.id, this.eventName, this.eventPrice, this.eventDescription,
      this.eventDateStart, this.eventDateFinish);
}

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;
  List<Event> eventList = [
    Event("1", "a", 123.0, "a desc", DateTime(2020, 9, 17, 13, 0, 0),
        DateTime(2020, 9, 17, 13, 0, 0)),
    Event("2", "b", 456.0, "b desc", DateTime(2020, 9, 17, 12, 0, 0),
        DateTime(2020, 9, 17, 13, 0, 0))
  ];

  Map<DateTime, List<Event>> convertToMap(List<Event> item) {
    Map<DateTime, List<Event>> result;
    for (int i = 0; i < item.length; i++) {
      Event data = item[i];
      //get the date and convert it to a DateTime variable
      //DateTime currentDate = data.eventDateStart;

      DateTime currentDate = DateTime(data.eventDateStart.year,
          data.eventDateStart.month, data.eventDateStart.day);

      List<Event> events = [];
      //add the event name to the the eventNames list for the current date.
      //search for another event with the same date and populate the eventNames List.
      for (int j = 0; j < item.length; j++) {
        //create temp calendarItemData object.
        Event temp = item[j];
        //establish that the temp date is equal to the current date
        if (DateTime(data.eventDateStart.year, data.eventDateStart.month,
                data.eventDateStart.day) ==
            DateTime(temp.eventDateStart.year, temp.eventDateStart.month,
                temp.eventDateStart.day)) {
          //add the event name to the event List.
          events.add(temp);
        } //else continue
      }

      //add the date and the event to the map if the date is not contained in the map
      if (result == null) {
        result = {currentDate: events};
      } else {
        result[currentDate] = events;
      }
    }
    print(result);
    print(result[DateTime(2020, 9, 17, 0, 0, 0)].length);
    return result;
  }

  void _incrementCounter() {
    convertToMap(eventList);
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

Upvotes: 1

Related Questions