Articles in this section
Category / Section

How to work with the Firebase database and the Flutter Calendar for appointments

5 mins read

In the Flutter Event Calendar, you can add the appointment data to FireBase database from selected value of the PopupMenuItem of the Flutter and fetch the values from the database assign it to the Flutter calendar events.

STEP 1: Add the required packages in Pubspec.yaml.

  syncfusion_flutter_calendar: ^19.1.58
  firebase_core: ^1.1.0
  cloud_firestore: ^1.0.7
  firebase_database: ^6.1.2

 STEP 2: Create a database in Firebase and store the appointment data in the database. Please refer the following link to create database and store the data.

Firebase data

STEP 3: Add a method for fetching data from the created database.

getDataFromDatabase() async {
  var value= FirebaseDatabase.instance.reference();
  var getValue=await value.child('CalendarAppointmentCollection').once();
  return getValue;
}

STEP 4: Call this method in initState() and based on the results value update the appointment value.

void initState() {
  getDataFromDatabase().then((results) {
    setState(() {
      if(results !=null) {
        querySnapshot = results;
      }
    });
  });
  super.initState();
}

STEP 5: Fetching the appointments from the database.

@override
Widget build(BuildContext context) {
  return Scaffold(
    body: _showCalendar(),
  );
}
 
_showCalendar() {
  if (querySnapshot != null) {
    List<Meeting> collection;
    var showData = querySnapshot.value;
    Map<dynamic, dynamic> values = showData;
    List<dynamic> key = values.keys.toList();
    if (values != null) {
      for (int i = 0; i < key.length; i++) {
        data = values[key[i]];
        collection ??= <Meeting>[];
        final Random random = new Random();
        collection.add(Meeting(
            eventName: data['Subject'],
            isAllDay: false,
            from: DateFormat('dd/MM/yyyy HH:mm:ss').parse(data['StartTime']),
            to: DateFormat('dd/MM/yyyy HH:mm:ss').parse(data['EndTime']),
            background: _colorCollection[random.nextInt(9)],
            resourceId: data['ResourceId']));
      }
    } else {
      return Center(
        child: CircularProgressIndicator(),
      );
    }
 
    return SfCalendar(
      view: CalendarView.timelineDay,
      allowedViews: [
        CalendarView.timelineDay,
        CalendarView.timelineWeek,
        CalendarView.timelineWorkWeek,
        CalendarView.timelineMonth,
      ],
      initialDisplayDate: DateTime(2020, 4, 5, 9, 0, 0),
      dataSource: _getCalendarDataSource(collection),
      monthViewSettings: MonthViewSettings(showAgenda: true),
    );
}
 
void _initializeEventColor() {
  this._colorCollection = new List<Color>();
  _colorCollection.add(const Color(0xFF0F8644));
  _colorCollection.add(const Color(0xFF8B1FA9));
  _colorCollection.add(const Color(0xFFD20100));
  _colorCollection.add(const Color(0xFFFC571D));
  _colorCollection.add(const Color(0xFF36B37B));
  _colorCollection.add(const Color(0xFF01A1EF));
  _colorCollection.add(const Color(0xFF3D4FB5));
  _colorCollection.add(const Color(0xFFE47C73));
  _colorCollection.add(const Color(0xFF636363));
  _colorCollection.add(const Color(0xFF0A8043));
}

STEP 6: Use the push() method for adding the appointment data to database based on the selected value from the PopMenuItem. push() method will create a random id in the database, and the set() method will contain the data from the form. The then() callback will execute after the data is added in the Firebase database. Also by using the remove() method, you can remove the entire data in the firebase database.

leading: PopupMenuButton<String>(
  icon: Icon(Icons.settings),
  itemBuilder: (BuildContext context) => options.map((String choice) {
    return PopupMenuItem<String>(
      value: choice,
      child: Text(choice),
    );
  }).toList(),
  onSelected: (String value) {
    if (value == 'Add') {
      final dbRef =
          FirebaseDatabase.instance.reference().child("CalendarAppointmentCollection");
      dbRef.push().set({
        "StartTime": '07/04/2020 07:00:00',
        "EndTime": '07/04/2020 08:00:00',
        "Subject": 'NewMeeting',
        "ResourceId": '0001'
      }).then((_) {
        Scaffold.of(context).showSnackBar(
            SnackBar(content: Text('Successfully Added')));
      }).catchError((onError) {
        print(onError);
      });
    } else if (value == 'Delete') {
      final dbRef =
          FirebaseDatabase.instance.reference().child("CalendarAppointmentCollection");
      dbRef.remove();
    }
  },
),

View sample in GitHub

Flutter firebase data with resource

 

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (6)
Please  to leave a comment
MY
Muhammad Yahya

Im trying implement this code into firestore, but i got so many error, do you have any documentaion for this calender and how its work with firestore? Thank you

IR
Indumathi Ravichandran

Hi Muhammad,

Thank you for contacting Syncfusion support.

For storing data to Firestore and retrieving calendar data from Firestore you need to create a sample in Firebase console and configure those project to Flutter calendar sample. Kindly refer the following links for the same.

Links: https://console.firebase.google.com/ https://firebase.google.com/docs/flutter/setup?platform=android

Also please find the sample link for the same. https://github.com/SyncfusionExamples/firebase-get-and-update-wth-flutter-event-calendar

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

Regards, Indumathi R

NP
Nguyen Phong

Hello, Im trying implement this code into firestore, but i this error: The getter 'keys' was called on null. Receiver: null Tried calling: keys

Error pic

IR
Indumathi Ravichandran

Hi Nguyen,

Thank you for contacting Syncfusion support.

Regarding Query: The getter 'keys' was called on null. Receiver: null Tried calling: keys

The mentioned error occurred due to mismatch appointment collection name. So, we need to mention the same collection name in Firebase and sample. For storing data to Firestore and retrieving calendar data from Firestore you need to create a sample in Firebase console and configure that project to Flutter calendar sample. Kindly refer the following links for the same.

Screenshot: https://www.syncfusion.com/downloads/support/directtrac/general/ze/Image-240798589.zip

Code snippet:

leading: PopupMenuButton<String>(
  icon: Icon(Icons.settings),
  itemBuilder: (BuildContext context) => options.map((String choice) {
    return PopupMenuItem<String>(
      value: choice,
      child: Text(choice),
    );
  }).toList(),
  onSelected: (String value) {
    if (value == 'Add') {
      final dbRef =
          FirebaseDatabase.instance.reference().child("**CalendarAppointmentCollection**");
      dbRef.push().set({
        "StartTime": '07/04/2020 07:00:00',
        "EndTime": '07/04/2020 08:00:00',
        "Subject": 'NewMeeting',
        "ResourceId": '0001'
      }).then((_) {
        Scaffold.of(context).showSnackBar(
            SnackBar(content: Text('Successfully Added')));
      }).catchError((onError) {
        print(onError);
      });
    } else if (value == 'Delete') {
      final dbRef =
          FirebaseDatabase.instance.reference().child("**CalendarAppointmentCollection**");
      dbRef.remove();
    }
  },
),

Links: https://console.firebase.google.com/ https://firebase.google.com/docs/flutter/setup?platform=android

Also please find the sample link for the same.

https://github.com/SyncfusionExamples/firebase-get-and-update-wth-flutter-event-calendar

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

Regards, Indumathi R

MA
Marcel

hello, I tried to implement this into my code but its not working, is there any way you could provide a new version of this? Im also ready to pay if necessary! I really need your help! Kind regards :)

IR
Indumathi Ravichandran

Hi Marcel,

We have modified the sample for getting the data from firebase database and ensured from our end. It was working fine as expected. We have attached the tested sample for the same. Please find the sample from the following link.

Sample link: https://www.syncfusion.com/downloads/support/directtrac/general/ze/FIREBA~3-1125991402

Please check the sample and let us know if you still facing the same issue? If not, please modify the sample based on your scenario and revert us with more details, it will be helpful for us to check on it and provide you solution at the earliest.

Regards, Indumathi R

MA
Marcel

the program never enters "if (querySnapshot != null)". Im not able to add an appointment to my database so the add function isnt working, and yeah its the same name in Firebase and the program

Access denied
Access denied