Flutter Syncfusion Calendar doesn't show data

2k Views Asked by At

I have a problem with SyncFusion's flutter calendar which is demonstrated by this screenshot enter image description here

As you see the calendar still get the data from my API but it doesn't show any meeting data on the calendar. FYI, I would like get the data with each time i click on each day, that why I'm using onViewChanged

Here is my full code:

import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:myhumgupdate/App/Config/palette.dart';
import 'package:myhumgupdate/Icon/dbicons.dart';
import 'package:myhumgupdate/Widgets/dialog_loading.dart';
import 'package:myhumgupdate/giangvien/Screens/XemTKB/TKBTheoNgay/tkbngay_viewmodel.dart';
import 'package:myhumgupdate/giangvien/models/meeting.dart';
import 'package:myhumgupdate/giangvien/models/meetingdata_source.dart';
import 'package:stacked/stacked.dart';
import 'package:syncfusion_flutter_calendar/calendar.dart';

class TKBNgay extends StatefulWidget {
  @override
  _TKBNgayState createState() => _TKBNgayState();
}

class _TKBNgayState extends State<TKBNgay> {
  DateTime date;

  List<DateTime> _blackoutDates = <DateTime>[];
  CalendarController _calendarController;
  CalendarController _onViewChanged;
  DateTime _chosenDate = DateTime.now();

  CalendarDataSource _calendarDataSource;
  dynamic scheduleViewBuilder;
  bool _showDatePickerButton = true;
  bool _allowViewNavigation = true;
  bool _showLeadingAndTrailingDates = true;
  DateTime _minDate;
  DateTime _maxDate;
  final List<CalendarView> _allowedViews = <CalendarView>[
    CalendarView.day,
    CalendarView.week,
    CalendarView.workWeek,
    CalendarView.month,
    CalendarView.schedule
  ];
  ViewChangedCallback viewChangedCallback;

  @override
  Widget build(BuildContext context) {
    return ViewModelBuilder<TKBNgayViewModel>.reactive(
        builder: (context, model, child) => SfCalendar(
              onViewChanged: (details) {
                List<DateTime> dates = details.visibleDates;
                model.getTkbNgay(dates[0]);
              },
              // onTap: (details) {
              //   DateTime date = details.date;
              //   model.getTkbNgay(date);
              // },
              controller: _calendarController,
              dataSource: MeetingDataSource(model.getDataSource),
              scheduleViewMonthHeaderBuilder: scheduleViewBuilder,
              // appointmentBuilder: appointmentBuilder,
              appointmentTimeTextFormat: 'hh:mm:ss a',
              initialDisplayDate: DateTime(DateTime.now().year,
                  DateTime.now().month, DateTime.now().day, 00, 45, 0),
              allowedViews: _allowedViews,
              showDatePickerButton: _showDatePickerButton,
              allowViewNavigation: _allowViewNavigation,
              blackoutDates: _blackoutDates,
              minDate: _minDate,
              maxDate: _maxDate,
              monthViewSettings: MonthViewSettings(
                  appointmentDisplayMode:
                      MonthAppointmentDisplayMode.appointment,
                  showTrailingAndLeadingDates: _showLeadingAndTrailingDates,
                  appointmentDisplayCount: 4),
              // timeSlotViewSettings: const TimeSlotViewSettings(
              //     minimumAppointmentDuration: Duration(minutes: 60)),
              timeSlotViewSettings: TimeSlotViewSettings(
                startHour: 0,
                endHour: 16,
                timeFormat: " H",
                timeIntervalHeight: 60,
                timeTextStyle: TextStyle(
                  color: Colors.black,
                  fontWeight: FontWeight.bold,
                ),
              ),
              selectionDecoration: BoxDecoration(
                color: Colors.transparent,
                border: Border.all(color: Colors.yellow, width: 2),
                shape: BoxShape.rectangle,
              ),
            ),
        viewModelBuilder: () => TKBNgayViewModel());
  }
}

void calendarTapped(CalendarTapDetails details) {
  if (details.targetElement == CalendarElement.viewHeader) {}
}

Widget appointmentBuilder(BuildContext context,
    CalendarAppointmentDetails calendarAppointmentDetails) {
  final Meeting appointment = calendarAppointmentDetails.appointments.first;
  return Column(
    children: [
      Container(
        width: calendarAppointmentDetails.bounds.width,
        height: calendarAppointmentDetails.bounds.height,
        // color: appointment.background,
        decoration: BoxDecoration(
          border: Border.all(
            color: Colors.black,
            width: 0.25,
          ),
          color: appointment.background,
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              '${appointment.tkb.maMonHoc} - ${appointment.tkb.tenMonHoc}',
              style: TextStyle(
                color: Palette.kSecondColor,
                fontWeight: FontWeight.w600,
                fontSize: 16.0,
              ),
            ),
            SizedBox(
              height: 5.0,
            ),
            Text(
              'Phòng: ${appointment.tkb.maPhongHoc} - Nhóm MH: ${appointment.tkb.nhom}',
              style: TextStyle(
                color: Palette.kSecondColor,
                fontWeight: FontWeight.w600,
                fontSize: 16.0,
              ),
            ),
            SizedBox(
              height: 5.0,
            ),
            Text(
              'Giảng viên: ${appointment.tkb.giaoVien}',
              style: TextStyle(
                color: Palette.kSecondColor,
                fontWeight: FontWeight.w600,
                fontSize: 16.0,
              ),
            ),
          ],
        ),
      )
    ],
  );
}

Here is my viewmodel code :

import 'dart:ui';

import 'package:intl/intl.dart';
import 'package:myhumgupdate/giangvien/models/meeting.dart';
import 'package:myhumgupdate/giangvien/models/thoikhoabieu_ngay.dart';
import 'package:myhumgupdate/giangvien/services/schedule.service.dart';
import 'package:stacked/stacked.dart';
import 'package:table_calendar/table_calendar.dart';

class TKBNgayViewModel extends BaseViewModel {
  List<ThoiKhoaBieuNgay> _tkbNgayModels;
  List<ThoiKhoaBieuNgay> get tkbNgayModels => _tkbNgayModels ?? [];
  List<Meeting> _getDataSource = [];

  ScheduleService _scheduleService = new ScheduleService();
  List<Meeting> get getDataSource => _getDataSource;

  CalendarController calendarController = CalendarController();
  DateFormat formatDateTitle = DateFormat("EEEE, dd/MM/yyyy", 'vi');
  String _currentTime = DateFormat("EEEE, dd/MM/yyyy", 'vi').format(DateTime.now());
  DateTime _timeSelect = DateTime.now();
  DateTime get timeSelect => _timeSelect;

  String get currentTime => _currentTime;
  DateTime timeNow = DateTime.now();
  DateFormat date = new DateFormat('dd/MM/y');
  int day = DateTime.now().day;

  getTkbNgay(DateTime dateTime) async {
    _currentTime = formatDateTitle.format(dateTime);
    _timeSelect = dateTime;


    String today = date.format(dateTime);
    var day = today.split("/");
    if (day[0].length < 2) return day[0] = '0${day[0]}';

    String dateParse = '${day[0]}/${day[1]}/${day[2]}';

    List<ThoiKhoaBieuNgay> getTKBNgay =
        await _scheduleService.getThoiKhoaBieuNgay(dateParse, true);

    _getDataSource.clear();
    if (getTKBNgay != null) {
      DateTime _startTime = timeNow;
      DateTime _endTime = timeNow;
      getTKBNgay.forEach((element) {
        _startTime = DateTime(timeNow.year, timeNow.month, timeNow.day,
            element.tietBatDau.toInt(), 0, 0);
        _endTime = _startTime.add(Duration(hours: element.soTiet.toInt()));
        _getDataSource.add(Meeting(
          eventName: element.tenMonHoc,
          from: _startTime,
          to: _endTime,
          subText: element.maPhongHoc,
          tkb: element,
          background: Color(0xFFFEFEA5),
        ));
      });
    } else {
      getTKBNgay = [];
    }

    _tkbNgayModels = getTKBNgay.toList();
    notifyListeners();
  }

  Comparator<ThoiKhoaBieuNgay> priceComparator =
      (a, b) => a.tietBatDau.compareTo(b.tietBatDau);
}
1

There are 1 best solutions below

0
On

Getting the visible date appointment details: You can get the appointment of the visible date details by using the getVisibleAppointments helper method of the Calendar data source. Please find the pub documentation link for the same.

Pub documentation link: https://pub.dev/documentation/syncfusion_flutter_calendar/latest/calendar/CalendarDataSource/getVisibleAppointments.html

Also, we have a KB document for showing the visible dates appointments in an alert window. Please find the KB document from the following link.

KB link: https://www.syncfusion.com/kb/12549/how-to-get-the-appointments-between-the-given-start-and-end-date-in-the-flutter-calendar

Also please find some helper methods of data source from the following UG documentation.

UG link: https://help.syncfusion.com/flutter/calendar/appointments#appointment-helper

We hope that this helps you. Please let us know if you need further assistance.