1

Here is my utils.dart code that generates static events, this file is then imported to another dart file where we have the table_calender. the

Future<List> ann = fetchadvertannouncements() is an api that i have created that fetches data from phpmyadmin, and the data is already fetched. The issue am having is how to display that data as calender events

import 'dart:collection';

import 'package:flutter/cupertino.dart';
import 'package:saajnairobi/announcementapi.dart';
import 'package:table_calendar/table_calendar.dart';

import '../advertannouncements.dart';

/// Example event class.
class Event {
  final String title;

  const Event(this.title);

  @override
  String toString() => title;
}

Future<List<Welcome>> ann =  fetchadvertannouncements();
/// Example events.
///
/// Using a [LinkedHashMap] is highly recommended if you decide to use a map.
final kEvents = LinkedHashMap<DateTime, List<Event>>(
  equals: isSameDay,
  hashCode: getHashCode,
)..addAll(_kEventSource);

final _kEventSource = Map.fromIterable(List.generate(50, (index) => index),
    key: (item) => DateTime.utc(kFirstDay.year, kFirstDay.month, item * 5),
    value: (item) => List.generate(
        item % 4 + 1, (index) => Event('Event $item | ${index + 1}')))
  ..addAll({
    kToday: [
      Event('Today\'s Event 1'),
      Event('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 kToday = DateTime.now();
final kFirstDay = DateTime(kToday.year, kToday.month - 3, kToday.day);
final kLastDay = DateTime(kToday.year, kToday.month + 3, kToday.day);

Here is the dart file:

import 'package:flutter/material.dart';
import 'package:saajnairobi/navdrawer.dart';
import 'package:table_calendar/table_calendar.dart';

import '../shared/utils.dart';

class TableEventsExample extends StatefulWidget {
  @override
  _TableEventsExampleState createState() => _TableEventsExampleState();
}

class _TableEventsExampleState extends State<TableEventsExample> {
  late final ValueNotifier<List<Event>> _selectedEvents;
  CalendarFormat _calendarFormat = CalendarFormat.month;
  RangeSelectionMode _rangeSelectionMode = RangeSelectionMode
      .toggledOff; // Can be toggled on/off by longpressing a date
  DateTime _focusedDay = DateTime.now();
  DateTime? _selectedDay;
  DateTime? _rangeStart;
  DateTime? _rangeEnd;

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

    _selectedDay = _focusedDay;
    _selectedEvents = ValueNotifier(_getEventsForDay(_selectedDay!));
  }

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

  List<Event> _getEventsForDay(DateTime day) {
    // Implementation example
    return kEvents[day] ?? [];
  }

  List<Event> _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);
    }
  }

  void _onRangeSelected(DateTime? start, DateTime? end, DateTime focusedDay) {
    setState(() {
      _selectedDay = null;
      _focusedDay = focusedDay;
      _rangeStart = start;
      _rangeEnd = end;
      _rangeSelectionMode = RangeSelectionMode.toggledOn;
    });

    // `start` or `end` could be null
    if (start != null && end != null) {
      _selectedEvents.value = _getEventsForRange(start, end);
    } else if (start != null) {
      _selectedEvents.value = _getEventsForDay(start);
    } else if (end != null) {
      _selectedEvents.value = _getEventsForDay(end);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(

      drawer: navdrawer(),
      
      body: Column(
        children: [
          Padding(
            padding: const EdgeInsets.fromLTRB(0,60,0,0),

            child: Container(
              decoration: const BoxDecoration(
                color: Colors.white,
              ),
              // transform: Matrix4.translationValues(0, 0, 0),
              // width: MediaQuery.of(context).size.width,
              // height: 15.h,
              height: MediaQuery.of(context).size.height / 6,
              child: Image.asset('assets/images/logo.jpg'),
            ),
          ),

          Expanded(
            child: Container(
              transform: Matrix4.translationValues(0.0, 0, 0.0),
                // padding: EdgeInsets.fromLTRB(20, 10, 20, 0),
                padding: const EdgeInsets.fromLTRB(0, 0, 0, 0),
                
                width: MediaQuery.of(context).size.width,
                // height: 85.h,
                decoration: const BoxDecoration(
                  borderRadius: BorderRadius.only(
                    topLeft: Radius.circular(31.0),
                    topRight: Radius.circular(31.0),
                  ),
                  color: Color.fromARGB(255, 235, 235, 235),
                ),

                

            child: Padding(
                padding: const EdgeInsets.fromLTRB(0, 0, 0, 0),
                child: Column(
                  children: [

              Container(
              // transform: Matrix4.translationValues(0.0, 10.0, 0.0),
              // padding: EdgeInsets.fromLTRB(20, 10, 20, 0),
              padding: EdgeInsets.fromLTRB(0, 10, 0, 10),
              
              width: MediaQuery.of(context).size.width,

              decoration: new BoxDecoration(
                borderRadius: BorderRadius.only(
                  topLeft: Radius.circular(31.0),
                  topRight: Radius.circular(31.0),
                ),
                color: Color(0xff2c6c42),
              ),
          
              child: Column(
                
              children: [
                  const Text("Calendar",
                        style: TextStyle(
                        fontFamily: 'ProximaNova',
                        color: Color(0xffffffff),
                        fontSize: 30,
                        fontWeight: FontWeight.w600,
                        fontStyle: FontStyle.normal,
                        ),
                      ),
                      
              ],
              
              ),

            ),

             Container(
                color: Color(0xff2c6c42),
                     child: new Container(
                     padding: const EdgeInsets.fromLTRB(0, 10, 0, 0),
                        
                    width: MediaQuery.of(context).size.width,
                        // height: 2,
                     decoration: const BoxDecoration(
                      borderRadius: BorderRadius.only(
                        topLeft: Radius.circular(31.0),
                        topRight: Radius.circular(31.0),
                      ),
                  color: Color.fromARGB(255, 235, 235, 235),
                      
                    ),
                    child:  Padding(
                      padding: EdgeInsets.fromLTRB(0, 10, 0, 10),
                      child: Center(
                       
                      ),
                    ),
                   ),
                   ),
                    

                    SingleChildScrollView(
                      child: TableCalendar<Event>(
                      firstDay: kFirstDay,
                      lastDay: kLastDay,
                      focusedDay: _focusedDay,
                      selectedDayPredicate: (day) => isSameDay(_selectedDay, day),
                      rangeStartDay: _rangeStart,
                      rangeEndDay: _rangeEnd,
                      calendarFormat: _calendarFormat,
                      rangeSelectionMode: _rangeSelectionMode,
                      eventLoader: _getEventsForDay,
                      startingDayOfWeek: StartingDayOfWeek.monday,
                      calendarStyle: CalendarStyle(
                  
                        todayTextStyle: TextStyle(
                          fontWeight: FontWeight.bold,
                          fontSize: 18,
                        ),
                        // Use `CalendarStyle` to customize the UI
                      
                        selectedDecoration: BoxDecoration(
                          color: Color(0xff2c6c42),
                          // borderRadius: BorderRadius.circular(50),                          
                        ),

                        todayDecoration: BoxDecoration(
                          color: Color.fromARGB(255, 136, 191, 155),
                          // borderRadius: BorderRadius.circular(50),
                        ),
                        outsideDaysVisible: false,
                      ),
                      onDaySelected: _onDaySelected,
                      onRangeSelected: _onRangeSelected,
                      onFormatChanged: (format) {
                        if (_calendarFormat != format) {
                          setState(() {
                            _calendarFormat = format;
                          });
                        }
                      },
                      onPageChanged: (focusedDay) {
                        _focusedDay = focusedDay;
                      },

                      headerStyle: HeaderStyle(
                        formatButtonVisible: true,
                        titleTextStyle: TextStyle(
                          color: Color.fromARGB(255, 9, 101, 22)
                          
                        ),
                        titleCentered: true,
                        formatButtonShowsNext: false,
                        formatButtonDecoration: BoxDecoration(
                          color: Color.fromARGB(255, 13, 87, 35),
                          borderRadius: BorderRadius.circular(40),
                        ),
                      ),
                    ),
                    ),

                  const SizedBox(height: 8.0),

                  Expanded(
                    child: ValueListenableBuilder<List<Event>>(
                      valueListenable: _selectedEvents,
                      builder: (context, value, _) {
                        return ListView.builder(
                          itemCount: value.length,
                          itemBuilder: (context, index) {
                            return Container(
                              margin: const EdgeInsets.symmetric(
                                horizontal: 12.0,
                                vertical: 4.0,
                              ),
                              decoration: BoxDecoration(
                                border: Border.all(
                                  color: Color.fromARGB(255, 51, 50, 50),
                                ),
                                borderRadius: BorderRadius.circular(12.0),
                              ),
                              child: ListTile(
                                onTap: () => print('${value[index]}'),
                                title: Text('${value[index]}', 
                                style: TextStyle(color: Color.fromARGB(255, 91, 90, 90)),
                                ),
                              ),
                            );
                          },
                        );
                      },
                    ),
                  ),

                  ],
                ),
              ),
            )
          ),
          
        ],
      ),
    );
  }
}

0 Answers0