Open In App

Flutter – Create Interactive Event Calendars

Last Updated : 04 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

This article outlines how to integrate event management functionality into a Flutter project, with a focus on adding and displaying events within a calendar interface. We will utilize the GetX package for routing and various utilities; alternative solutions are also available. The get_cli tool will be employed to create a well-structured Flutter project, helping us generate complex project hierarchies, including views, controllers, and pages.

The primary focus of this article is on dynamically rendering events within the Flutter calendar. We will implement a demonstration program that displays events and enables users to create new events directly within the calendar interface. For this purpose, we will use the table_calendar package, which seamlessly integrates with Flutter and offers a comprehensive solution for managing events in a calendar environment.

Flutter_Create-Interactive-Event-Calendars


Use Case Or Why Integrate Event Calendar in a Flutter App

Integrating an event calendar into a Flutter app has several use cases. Primarily, it helps users manage their appointments, meetings, and social engagements, keeping them organized. Additionally, it can display events relevant to the app, such as local happenings in a news app or interests in a social media app. Furthermore, it can enable innovative features, like tracking workouts in a fitness app or showing upcoming flights and hotel reservations in a travel app.

Benefits of using the GetX package

  • Easy to learn and use: GetX is a user-friendly state management library for Flutter, making state management straightforward with intuitive APIs.
  • Powerful and flexible: It supports various features like dependency injection, reactive programming, and navigation management, suitable for diverse Flutter apps.
  • Lightweight and efficient: GetX is minimal in resource usage and highly scalable, ideal for both small and large projects.

Benefits of using the get_cli tool

  • Scaffold’s projects with GetX: Quickly set up new Flutter projects with GetX integrated, saving configuration time.
  • Generates code for components: Automates code generation for pages, controllers, and bindings, reducing manual coding effort.
  • Offers helpful commands: Includes commands for managing dependencies, running tests, and generating documentation, enhancing development efficiency.

What is the table_calendar package?

The table_calendar package is a Flutter library that offers a highly customizable and feature-rich range selection, multiuser-friendly and comic events and holidays, vertical auto-sizing, and various calendar formats (month, two weeks, and week). In simple terms, the table_calendar package is an excellent tool for integrating a calendar into your Flutter app, providing numerous features and customization opportunities.

Here are some examples of how you can utilize the table_calendar package in your Flutter app:

  • Display a calendar of upcoming events, such as appointments, meetings, and social engagements.
  • Show a calendar for events related to your app’s content or purpose, like upcoming news stories or social media events.
  • Use a calendar to track users’ progress toward goals, such as fitness or learning objectives.
  • Allow users to select dates and times for appointments or reservations using the calendar.

Step by Step Implementation

Step 1: Install get_cli globally

To install get_cli global,y we need to run this command from the root:

flutter pub global activate get_cli

If you are running one of these commands successfully, then you have get_cli installed on your system,m and now we can start using it.

pub_global_command

For more detailed instructions search get_cli on pub.dev.

Step 2: Create a new Flutter Application

Create a new Flutter application using the command Prompt. To create a new app, write the below command and run it.

flutter create app_name

To know more about it refer this article: Creating a Simple Application in Flutter


Step 3: Adding the Dependency

To add the dependency to the pubspec.yaml file, add  table_calendar as a dependency in the dependencies part of the pubspec.yaml file, as shown below:

Dart
dependencies:
     flutter:
       sdk: flutter
     table_calendar: ^3.2.0

Now run the below command in the terminal.

flutter pub get

Or

Run the below command in the terminal.

flutter pub add table_calendar


Step 4: Import dependencies

To use libraries, import all of them in the respective .dart file,

import 'package:table_calendar/table_calendar.dart';

Step 5 : Initialize and get

Open the root of the project in a terminal, and run the following command to start creating folder structure as per get_cli.

get init

Please select one option: 1) GetX Pattern or 2) CLEAN. Type “1” and press Enter.

choose_architecture

If your lib folder already has some code files, it will prompt you to overwrite. Type “1” and press Enter.

overwrite

Then it will remove existing packages and add required packages.

remove_and_add_packages

And also adds the required package.

add_required_files

Architecture:

Once done your project structure would look like this, but you won’t be having create_event and detail_screen directory as of now.

folder_structure

Those will be created once you run the following command:

 get create page:create_event

Project Structure:

Below is the entire project structure you would have by now.

lib
└── app
    ├── data
    ├── modules
    │   ├── create_event
    │   │   ├── bindings
    │   │   │   └── create_event_binding.dart
    │   │   ├── controllers
    │   │   │   └── create_event_controller.dart
    │   │   ├── views
    │   │   │   └── create_event_view.dart
    │   ├── home
    │   │   ├── bindings
    │   │   │   └── home_binding.dart
    │   │   ├── controllers
    │   │   │   └── home_controller.dart
    │   │   ├── views
    │   │   │   └── home_view.dart
    ├── routes
    │   ├── app_pages.dart
    │   ├── app_routes.dart
    ├── main.dart

Now we are going to start the actual coding part.

Step 6: Create an Event Model

This Event Model is used to represent data. So, create a new folder in the data folder named “models” create a new file named “event_model.dart” and paste the below code.

event_model.dart:

Dart
// A model representing an event with a title.
class EventModel {
  final String title;
  EventModel({required this.title});
}


Step 7: Update Controllers

Controllers manage the application’s logic and data, serving as the connection between the user interface and the data.

home_controller.dart :

Dart
import 'package:get/get.dart';
import '../../../data/models/event_model.dart';

// Controller for managing calendar events in the home view.

// Uses GetX state management for reactive updates.
class HomeController extends GetxController {
      
      // The currently selected day in the calendar.
      var selectedDay = DateTime.now().obs;
    
      // The currently focused day in the calendar.
      var focusedDay = DateTime.now().obs;
    
      // A map storing events, where each key is a date (DateTime),
      // and the value is a list of events occurring on that day.
      var events = <DateTime, List<EventModel>>{}.obs;
    
      // Retrieves events for a specific day.
      // If no events exist for the given day, returns an empty list.
      List<EventModel> getEventsForDay(DateTime day) {
        return events[day] ?? [];
      }
    
      // Adds a new event to the specified date.
      // If the date already exists in the map, it appends the event.
      // Otherwise, it creates a new entry for the date.
      void addEvent(DateTime date, String title) {
        if (events.containsKey(date)) {
          events[date]!
              .add(EventModel(title: title)); // Append event to existing list
        } else {
          events[date] = [
            EventModel(title: title)
          ]; // Create a new list for this date
        }
        
        // Manually refresh to trigger UI updates
        events.refresh(); 
      }
}


What HomeController Do?

  • This component manages the selected and focused days of the calendar.
  • It stores events in a map where each date is associated with a list of EventModel objects. It provides a method called `getEventsForDay()` to fetch events for a specific day.
  • Additionally, it includes the `addEvent()` function, which allows users to add an event to the selected date.


create_event_controller.dart:

Dart
import 'package:get/get.dart';
import '../../home/controllers/home_controller.dart';

// Controller for creating events using GetX.
class CreateEventController extends GetxController {
  
  // Observable event title
  var eventTitle = ''.obs; 

  // Saves the event if the title is not empty.
  void saveEvent() {
        if (eventTitle.value.isNotEmpty) {
          
          // Get instance of HomeController
          HomeController homeController = Get.find(); 
          
          // Add event
          homeController.addEvent(homeController.selectedDay.value, eventTitle.value);
          
          // Close screen 
          Get.back(); 
        }
  }
}


What CreateEventController do?

  • Stores the title of the event (eventTitle).
  • The saveEvent() function is triggered when the “Save Event” button is clicked.


Step 8: Update Views

Views determine the appearance of the user interface (UI) and how it interacts with the controller.

home_view.dart:

Dart
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:table_calendar/table_calendar.dart';
import '../controllers/home_controller.dart';
import '../../create_event/views/create_event_view.dart';

// A stateless widget that displays an event calendar
// and a list of events for the selected day.

// Uses GetX for state management and navigation.
class HomeView extends StatelessWidget {
  
  // Initialize the HomeController using
  // Get.put() for dependency injection.
  final HomeController controller = Get.put(HomeController());

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Event Calendar'),
        backgroundColor: Colors.green,
        foregroundColor: Colors.white,
      ),

      body: Column(
        children: [
            
          // Calendar widget wrapped with Obx to update
          // dynamically when the selected date changes.
          Obx(() => TableCalendar(
              
                // Currently focused day.
                focusedDay: controller.focusedDay.value,
                
                // Earliest selectable date.
                firstDay: DateTime.utc(2020, 1, 1),
                
                // Latest selectable date.
                lastDay: DateTime.utc(2030, 12, 31),

                /// Determines whether a day is selected.
                selectedDayPredicate: (day) =>
                    isSameDay(controller.selectedDay.value, day),

                // Updates the selected and focused days when a date is tapped.
                onDaySelected: (selectedDay, focusedDay) {
                  controller.selectedDay.value = selectedDay;
                  controller.focusedDay.value = focusedDay;
                },

                // Loads events for the selected day.
                eventLoader: controller.getEventsForDay,
              )),

          // Expanded widget to ensure the event
          // list takes up remaining screen space.
          Expanded(
            child: Obx(() {
                
              // Retrieves the list of events for the selected day.
              final events =
                  controller.getEventsForDay(controller.selectedDay.value);

              // Displays the events in a ListView.
              return ListView.builder(
                  
                // Number of events for the selected day.
                itemCount: events.length,
                itemBuilder: (context, index) => ListTile(
                    
                  // Displays event title.
                  title: Text(events[index].title),
                ),
              );
            }),
          ),
        ],
      ),

      // Floating action button to navigate
      // to the event creation page.
      floatingActionButton: FloatingActionButton(
        backgroundColor: Colors.green,
        foregroundColor: Colors.white,
        child: Icon(Icons.add),

        // Navigates to CreateEventView when pressed.
        onPressed: () => Get.to(() => CreateEventView()),
      ),
    );
  }
}


What HomeView do?

  • Displays a calendar (TableCalendar) and highlights the selected day.
  • It uses Obx() to dynamically update the UI when the selected day changes.
  • The controller.getEventsForDay() method is called to display events.
  • The CreateEventView opens when the floating button is pressed.


create_event_view.dart:

Dart
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../controllers/create_event_controller.dart';

// A stateless widget responsible for creating a new event.
// Uses GetX for state management and dependency injection.
class CreateEventView extends StatelessWidget {
  
  // Initialize the CreateEventController using
  // Get.put() for dependency injection.
  final CreateEventController controller = Get.put(CreateEventController());

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Add Event'),
        backgroundColor: Colors.green,
        foregroundColor: Colors.white,
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: [
            
            // Text field to enter the event title.
            
            // Updates the eventTitle variable in
            // the controller on text change.
            TextField(
              decoration: InputDecoration(labelText: 'Event Title'),
              
              // Updates the controller state
              onChanged: (value) => controller.eventTitle.value = value,
            ),
            SizedBox(height: 20),

            // Button to save the event. Calls the
            // saveEvent method in the controller.
            ElevatedButton(
              style: ElevatedButton.styleFrom(
                backgroundColor: Colors.green,
                foregroundColor: Colors.white,
              ),
              onPressed:
                  controller.saveEvent, 
              child: Text('Save Event'),
            ),
          ],
        ),
      ),
    );
  }
}


What CreateEventView do?

  • Enables users to enter an event title.
  • Updates the event title in the controller and invokes saveEvent() when the “Save Event” button is clicked.


Step 9: Run the Application

Run the below command in the terminal.

flutter run

To Check the complete source code please Click here.

Output:




Next Article

Similar Reads