Articles in this section
Category / Section

How to get Datetime details while tapping the Flutter Calendar

3 mins read

In the Flutter Event Calendar, you can get the tapped `DateTime` details of the header, view header, and calendar cell using the `OnTap` event.

 

Getting tapped element details

 

STEP 1: Inside the state set the default values for alert dialog texts.

CalendarController _controller = CalendarController();
String? _text='', _titleText='';
Color? _headerColor, _viewHeaderColor, _calendarColor;

STEP 2: Trigger the `onTap` callback of the flutter calendar. Please find the following code for the calendar.

Expanded(
  child: SfCalendar(
    viewHeaderStyle:
        ViewHeaderStyle(backgroundColor: _viewHeaderColor),
    backgroundColor: _calendarColor,
    view: CalendarView.week,
    controller: _controller,
    allowedViews: [
      CalendarView.day,
      CalendarView.week,
      CalendarView.workWeek,
      CalendarView.month,
      CalendarView.timelineDay,
      CalendarView.timelineWeek,
      CalendarView.timelineWorkWeek
    ],
    onTap: calendarTapped,
  ),
),

STEP 3: Using the `OnTap` event, you can get the tapped target element details such as header, view header, calendar cells, agenda view, and get the date and time values from the callback and assign it to the content of the alert dialog widget. Please find the example for header, view header and cells.

void calendarTapped(CalendarTapDetails details) {
  if (details.targetElement == CalendarElement.header) {
    _text = DateFormat('MMMM yyyy').format(details.date!).toString();
    _titleText = 'Header';
  } else if (details.targetElement == CalendarElement.viewHeader) {
    _text = DateFormat('EEEE dd, MMMM yyyy').format(details.date!).toString();
    _titleText = 'View Header';
  } else if (details.targetElement == CalendarElement.calendarCell) {
    _text = DateFormat('EEEE dd, MMMM yyyy').format(details.date!).toString();
    _titleText = 'Calendar cell';
  }
  showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Container(child: new Text(" $_titleText")),
          content: Container(child: new Text(" $_text")),
          actions: <Widget>[
            new TextButton(
                onPressed: () {
                  Navigator.of(context).pop();
                },
                child: new Text('close'))
          ],
        );
      });
}

View sample in GitHub

Flutter calendar tapped elements

 

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments
Please  to leave a comment
Access denied
Access denied