LostTexan
LostTexan

Reputation: 891

Adding events to table_calendar

I am very new to flutter/Dart programming and am confused by the code below. I didn't write the code but I would like to use it to display event markers on the calendar grid of the table_calendar plugin.

class calEvent {
  final String title;

  const calEvent(this.title);

  @override
  String toString() => title;
}

/// Example events.
///
/// Using a [LinkedHashMap] is highly recommended if you decide to use a map.
final kEvents = LinkedHashMap<DateTime, List<calEvent>>(
  equals: isSameDay,
  hashCode: getHashCode,
)..addAll(_kEventSource);
**<<<<<<  I think FirestoreService().getEvent() would go here but I don't know how to add it or convert from Stream<List<Event>> to LinkedHashMap<DateTime, List<calEvent>>  >>>>>>**
final _kEventSource = Map.fromIterable(List.generate(50, (index) => index),
    key: (item) => DateTime.utc(2020, 10, item * 5),
    value: (item) => List.generate(
        item % 4 + 1, (index) => calEvent('Event $item | ${index + 1}')))
  ..addAll({
    DateTime.now(): [
      calEvent('Today\'s Event 1'),
      calEvent('Today\'s Event 2'),
    ],
  });

int getHashCode(DateTime key) {
  return key.day * 1000000 + key.month * 10000 + key.year;
}

/// Returns a list of [DateTime] objects from [first] to [last], inclusive.
List<DateTime> daysInRange(DateTime first, DateTime last) {
  final dayCount = last.difference(first).inDays + 1;
  return List.generate(
    dayCount,
        (index) => DateTime.utc(first.year, first.month, first.day + index),
  );
}

final kNow = DateTime.now();
final kFirstDay = DateTime(kNow.year, kNow.month - 3, kNow.day);
final kLastDay = DateTime(kNow.year, kNow.month + 3, kNow.day);

I create events on another page and store them in a Firebase collection. I can pull those events from the collection into a Stream<DateTime, List> but then I want to display them on the table_calendar grid based on the day they should occur. This code does this very well but not from a firebase collection. I want to implement it into my code but use code for pulling events from the Firebase collection as the source.

My problem is that I don't understand how/where to put my code in the _kEventSource code. I am attaching a file with some of my code so you can see what I am doing.

I would greatly appreciate advice on this.

Here is the code for building the table_calendar:

This is the code that builds the basic calendar framework and builds the event list below the calendar grid.

class _AppointmentCalendarScreenState extends State<AppointmentCalendarScreen> with TickerProviderStateMixin {
  late final ValueNotifier<List<calEvent>> _selectedEvents;
  late StreamController<Map<DateTime, List>> _streamController;
  CalendarFormat _calendarFormat = CalendarFormat.month;
  RangeSelectionMode _rangeSelectionMode = RangeSelectionMode
      .toggledOff; // Can be toggled on/off by longpressing a date
    
  List<calEvent> _getEventsForDay(DateTime day) {
    // Implementation example
    return kEvents[day] ?? [];
  }

  List<calEvent> _getEventsForRange(DateTime start, DateTime end) {
    // Implementation example
    final days = daysInRange(start, end);

    return [
      for (final d in days) ..._getEventsForDay(d),
    ];
  }

  void _onDaySelected(DateTime selectedDay, DateTime focusedDay) {
    if (!isSameDay(_selectedDay, selectedDay)) {
      setState(() {
        _selectedDay = selectedDay;
        _focusedDay = focusedDay;
        _rangeStart = null; // Important to clean those
        _rangeEnd = null;
        _rangeSelectionMode = RangeSelectionMode.toggledOff;
      });

      _selectedEvents.value = _getEventsForDay(selectedDay);
    }
  }


  @override
  Widget build(BuildContext context) {
    final eventProvider = Provider.of<EventProvider>(context);
    FirebaseFirestore _db = FirebaseFirestore.instance;

    return Scaffold(
      appBar: AppBar(
        automaticallyImplyLeading: false,
        title: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Image.asset('assets/images/Appbar_logo.png',
                fit: BoxFit.cover, height: 56),
          ],
        ),
      ),
      backgroundColor: Colors.white,
      resizeToAvoidBottomInset: false,
      body: Column(
        mainAxisSize: MainAxisSize.max,
        children: <Widget>[
          StreamBuilder( **<<<<  I get the events from Firebase here**
            stream: **_firestoreService.getEventStream(_selectedDay)**,
            builder: (context, AsyncSnapshot <List<Event>> eventsSnapShot) {
              if (eventsSnapShot.hasData) {
                var doc = eventsSnapShot.data!;
                for (int i = 0; i < doc.length; i++ ) {
                }
                return _buildTableCalendar();
              } else {
                return CircularProgressIndicator();
              }
            },
          ),

          const SizedBox(height: 8.0),

        ],
      ),
    );
  }

   **This is where the calendar grid is built**
  Widget _buildTableCalendar() {
    return TableCalendar(
      firstDay: kFirstDay,
      lastDay: kLastDay,
      focusedDay: _selectedDay,
      selectedDayPredicate: (day) => isSameDay(_selectedDay, day),
      locale: 'en_US',
      eventLoader: _getEventsForDay, // **This is important**
      //holidays: _holidays,
      
      ),

      onDaySelected: _onDaySelected,
      //onVisibleDaysChanged: _onVisibleDaysChanged,
      //onCalendarCreated: _onCalendarCreated,
      
    );
  }

This is the code for the call, FirestoreService().getEvent(), I use to get the events from the Firebase collection:

Stream<List<Event>> getEventStream(DateTime dateTime) async* {
    yield* _db.collection('agency').doc(globals.agencyId).collection('event')
        .where('eventDate', isGreaterThanOrEqualTo: Timestamp.fromDate(dateTime))
        .snapshots().map((snapshot) => snapshot.docs
        .map((document) => Event.fromFirestore(document.data()))
        .toList());
  }

This is the Event data model:

class Event {
  final String? eventName;
  //final TimeOfDay eventStartTime;
  final DateTime? eventStartTime;
  final String? eventDuration;
  final DateTime? eventDate;
  final String? eventDescription;
  final String? agentId;
  final String? agencyId;


  Event(
      {this.eventName,
      this.eventStartTime,
      this.eventDuration,
      this.eventDate,
      this.eventDescription,
      this.agentId,
      this.agencyId});

  Map<String, dynamic> toMap() {
    return {
      'eventName': eventName,
      'eventStartTime': eventStartTime,
      'eventDuration': eventDuration,
      'eventDate': eventDate,
      'eventDescription': eventDescription,
      'agentId': agentId,
      'agencyId': agencyId,
    };
  }

  // pass in a map and get an object back
  Event.fromFirestore(Map<String, dynamic> firestore)
      : eventName = firestore['eventName'],
        eventStartTime = firestore['eventStartTime'].toDate(),
        eventDuration = firestore['eventDuration'],
        eventDate = firestore['eventDate'].toDate(),
        eventDescription = firestore['eventDescription'],
        agentId = firestore['agentId'],
        agencyId = firestore['agencyId'];
}

Upvotes: 2

Views: 5990

Answers (1)

nicks101
nicks101

Reputation: 1191

Before kEvents, you have to make another map.
These are the steps with code snippets.

  • Get data from firebase (List<Event>)
    You are already doing this.
    Let's called this snapshot.data

  • Map these events to kEventSource.

 Map<DateTime, List<Event>> kEventSource = {};

    (snapshot.data).forEach((element) {
      kEventSource[DateTime(  
        element.time.year,
        element.time.month,
        element.time.day,
      )] = kEventSource[DateTime(
                element.time.year,
                element.time.month,
                element.time.day,
              )] !=
              null
          ? [
              ...kEventSource[DateTime(
                element.time.year,
                element.time.month,
                element.time.day,
              )],
              element
            ]
          : [element];
    });

Now we have a map data structure with dateTime as key and list of events on that day as value.
Example:

{
  "2 July 2021" : [Event1, Event2, ...],
  ...
}
  • Now kEvents is defined.
final kEvents = LinkedHashMap<DateTime, List<Event>>(
      equals: isSameDay,
      hashCode: getHashCode,
    )..addAll(kEventSource);

isSameDay functions come from the package itself.
Source code:

/// Checks if two DateTime objects are the same day.
/// Returns `false` if either of them is null.
bool isSameDay(DateTime? a, DateTime? b) {
  if (a == null || b == null) {
    return false;
  }

  return a.year == b.year && a.month == b.month && a.day == b.day;
}

Same for getHashCode. Though you can modify it.
Source Code:

  int getHashCode(DateTime key) {
    return key.day * 1000000 + key.month * 10000 + key.year;
  }

Now you have the KEvents, so you can use others features like selecting in range, etc.

Refernce: table_calender

I'll encourage you to look at the examples provided by the package author.

Upvotes: 5

Related Questions