Flutter: type 'Event' is not a subtype of type 'List<dynamic>'

Viewed 498

i'm using TableCalendar to display event from Firebase. I "successfully" displayed them in calendar, but day's with events colored red with error type 'Event' is not a subtype of type 'List<dynamic>'. I followed guides on pub dev page of package to display events. How can i fix it? I wan't to only display events on calendar without title

My main code:

  @override
  void initState() {
    super.initState();
    getEvents();
  }

  getEvents() async {
    var data = await FirebaseFirestore.instance.collection('events').get();
    List<Event> eventList = [];

    for (int i = 0; i < data.docs.length; i++) {
      var time = (data.docs[i]['date'] as Timestamp).toDate();
      var title = Event(data.docs[i]['title']);
      map[time] = title;
    }

    print(map);
  }

  List _getEventsForDay(DateTime day) {
    final events = LinkedHashMap(equals: isSameDay, hashCode: getHashCode)
      ..addAll(map);
    return events[day] ?? [];
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: appbar('title'),
      body: SafeArea(
        child: TableCalendar(
          firstDay: kFirstDay,
          lastDay: kLastDay,
          focusedDay: _focusedDay,
          eventLoader: (day) {
            return _getEventsForDay(day);
          },
        ),
      ),
    );
  }

My model file:

class Event {
  final String title;

  const Event(this.title);

  @override
  String toString() => title;
}

Map<DateTime, dynamic> map = {};

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

final kToday = DateTime.now();
final kFirstDay = DateTime(kToday.year, kToday.month - 1, kToday.day);
final kLastDay = DateTime(kToday.year, kToday.month + 1, kToday.day);
1 Answers

The problem is in the for loop where you are casting firestore data to the map

    for (int i = 0; i < data.docs.length; i++) {
      var time = (data.docs[i]['date'] as Timestamp).toDate();
      var title = Event(data.docs[i]['title']);
      map[time] = title;
    }

Accroding to the documentation table_calender #event

_getEventsForDay() can be of any implementation. For example, a Map<DateTime, List<T>> can be used:

The map should be a subtype of Map<DateTime, List<T>> but you are casting an event instead of the list.

So change your code as below and add title in a List<Event>

    for (int i = 0; i < data.docs.length; i++) {
      var time = (data.docs[i]['date'] as Timestamp).toDate();
      var title = Event(data.docs[i]['title']);
      map[time] = [title];
    }
  • To always prevent this problem from happening and code readability specify the type of variables when declaring them
Related