Calendar Table Flutter not save neither show events in first day with Provider

43 Views Asked by At

I'm working in project that contains a page with Table Calendar dependence. I'm trying save events day per day using provider. But when I try save events as soon as I open the screen, the data does not persist. It only works when I tap another day and try to save the data.

class CalendarScreen extends StatefulWidget {
  const CalendarScreen({super.key});

  @override
  State<CalendarScreen> createState() => _CalendarScreenState();
}

class _CalendarScreenState extends State<CalendarScreen> {
  DateTime _focusedDay = DateTime.now();
  DateTime? _selectedDay;
  final TextEditingController _titleEventController = TextEditingController();
  final DateTime beginSemester = DateTime(2024, 1);
  final DateTime endSemester = DateTime(2024, 6, 30);
  late final ValueNotifier<List<Event>> _selectedEvents;

  EventsDay? providerEventsDay;
  dynamic listEventsDay;
  bool isEventLoading = true;

  @override
  void initState() {
    super.initState();
    _selectedDay = _focusedDay;
    _selectedEvents = ValueNotifier(_getEventsForDay(_selectedDay!));
  }

  @override
  void dispose() {
    _selectedEvents.dispose();
    super.dispose();
  }

  @override
  void didChangeDependencies() {
    if (isEventLoading) {
      providerEventsDay = Provider.of<EventsDay>(context);
      listEventsDay = providerEventsDay!.eventsDay.keys.toList();
      isEventLoading = false;
    }
    super.didChangeDependencies();
  }

  void _onDaySelected(DateTime selectedDay, DateTime focusedDay) {
    if (!isSameDay(_selectedDay, selectedDay)) {
      setState(() {
        _focusedDay = focusedDay;
        _selectedDay = selectedDay;
        _selectedEvents.value = _getEventsForDay(selectedDay);
      });
    }
  }

  List<Event> _getEventsForDay(DateTime day) {
    return providerEventsDay?.eventsDay[day] ?? [];
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context).colorScheme;
    final deviceSize = MediaQuery.of(context).size;

    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        actionsIconTheme: IconThemeData(
          color: theme.primary,
        ),
        shape: const Border(bottom: BorderSide(color: Color(0xFFE5E5E5))),
        leading: IconButton(
          icon: const Icon(Icons.chevron_left, color: Color(0xFFA3A3A3)),
          onPressed: () => Navigator.of(context).pop(),
        ),
        title: const Text(
          "Calendário",
          style: TextStyle(fontWeight: FontWeight.w600),
        ),
        backgroundColor: Colors.white,
        actions: [
          IconButton(
            onPressed: () {
              print(listEventsDay);
              showDialog(
                context: context,
                builder: (context) {
                  return CalendarModal(
                    titleEventController: _titleEventController,
                    fn: () {
                      providerEventsDay!.addEvent(Event(
                          title: _titleEventController.text,
                          eventData: _selectedDay!));
                      _titleEventController.clear();
                      Navigator.of(context).pop();
                      _selectedEvents.value = _getEventsForDay(_selectedDay!);
                    },
                  );
                },
              );
            },
            icon: const Icon(Icons.add),
          ),
        ],
      ),
      body: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Expanded(
            child: Column(
              children: [
                SizedBox(
                  width: deviceSize.width * 0.9,
                  child: TableCalendar(
                    locale: ("pt_BR"),
                    rowHeight: 60,
                    calendarStyle: CalendarStyle(
                      markersMaxCount: 1,
                      markersAutoAligned: false,
                      markersAlignment: Alignment.topRight,
                      markersOffset: const PositionedOffset(top: 4, end: 4),
                      markerDecoration: const BoxDecoration(
                        color: Color(0xFF16A34A),
                        shape: BoxShape.circle,
                      ),
                      selectedDecoration: BoxDecoration(
                        color: theme.primary,
                        shape: BoxShape.circle,
                      ),
                      selectedTextStyle: const TextStyle(
                        fontWeight: FontWeight.w600,
                        color: Colors.white,
                      ),
                      todayDecoration: const BoxDecoration(
                        color: Color(0xFF93C5FD),
                        shape: BoxShape.circle,
                      ),
                      todayTextStyle: const TextStyle(
                        fontWeight: FontWeight.w600,
                        color: Colors.white,
                      ),
                    ),
                    headerStyle: HeaderStyle(
                      leftChevronVisible: false,
                      rightChevronVisible: false,
                      formatButtonVisible: false,
                      titleCentered: true,
                      headerPadding: EdgeInsets.symmetric(
                          vertical: deviceSize.width * 0.05),
                      titleTextFormatter: (date, locale) =>
                          DateFormat.yMMMM(locale)
                              .format(date)[0]
                              .toUpperCase() +
                          DateFormat.yMMMM(locale).format(date).substring(1),
                      titleTextStyle: TextStyle(
                          fontWeight: FontWeight.w600,
                          fontSize: deviceSize.width * 0.05),
                    ),
                    onDaySelected: _onDaySelected,
                    selectedDayPredicate: (day) => isSameDay(_selectedDay, day),
                    eventLoader: (day) => _getEventsForDay(day),
                    daysOfWeekStyle: DaysOfWeekStyle(
                      weekdayStyle: const TextStyle(
                          color: Color(0xFFA3A3A3),
                          fontWeight: FontWeight.w600),
                      weekendStyle: const TextStyle(
                          color: Color(0xFFA3A3A3),
                          fontWeight: FontWeight.w600),
                      dowTextFormatter: (date, locale) => DateFormat.E(locale)
                          .format(date)
                          .toUpperCase()
                          .substring(0, 3),
                    ),
                    onPageChanged: (focusedDay) {
                      _focusedDay = focusedDay;
                    },
                    pageJumpingEnabled: true,
                    firstDay: beginSemester,
                    lastDay: endSemester,
                    focusedDay: _focusedDay,
                  ),
                ),
                SizedBox(
                  width: deviceSize.width * 0.9,
                  child: const Divider(
                    color: Color(0xFFE5E5E5),
                  ),
                ),
                Expanded(
                  child: ValueListenableBuilder<List<Event>>(
                    valueListenable: _selectedEvents,
                    builder: (context, value, _) {
                      return SizedBox(
                        width: deviceSize.width * 0.9,
                        child: ListView.separated(
                          separatorBuilder: (contex, index) =>
                              const SizedBox(height: 10),
                          itemCount: value.length,
                          itemBuilder: (context, index) => Container(
                            padding: const EdgeInsets.all(12),
                            decoration: BoxDecoration(
                              border: Border.all(
                                color: theme.primary,
                              ),
                              borderRadius: BorderRadius.circular(8),
                            ),
                            child: Text(
                              value[index].title,
                              style: const TextStyle(
                                fontWeight: FontWeight.w500,
                                fontSize: 16,
                              ),
                            ),
                          ),
                        ),
                      );
                    },
                  ),
                )
              ],
            ),
          ),
        ],
      ),
    );
  }
}

I would like the data to be kept saved in my calendar even if the user navigate for other pages

0

There are 0 best solutions below