Articles in this section
Category / Section

How to perform the CRUD operations in Flutter Calendar using Firebase database

In the Flutter Event Calendar, perform CRUD operation on appointments using Firebase database.

Refer to the following guidelines to create the Firebase database.

https://firebase.google.com/docs/flutter/setup?platform=android#create-firebase-project

For detailed instructions on adding appointments to Firebase database and displaying them in Flutter calendar, see

https://www.syncfusion.com/kb/12067/how-to-work-with-the-firebase-database-and-the-flutter-calendar-for-appointments

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: Fetch the data from the Firebase database and subscribe to the database query using the listen method. Unsubscribe using cancel method.

getDataFromDatabase() async {
  var getValue = await meetingQuery.once();
  wireEvents(meetingQuery);
  return getValue;
}
 
void wireEvents(Query meetingQuery) {
  onMeetingAddedSubscription =
      meetingQuery.onChildAdded.listen(onMeetingAdded);
  onMeetingDeletedSubscription =
      meetingQuery.onChildRemoved.listen(onMeetingRemoved);
  onMeetingUpdatedSubscription =
      meetingQuery.onChildChanged.listen(onMeetingChanged);
}
 
@override
void dispose() {
  onMeetingAddedSubscription.cancel();
  onMeetingDeletedSubscription.cancel();
  onMeetingUpdatedSubscription.cancel();
  super.dispose();
}

STEP 3: In initState() populate the appointments from the Firebase database, using the fetched result by converting to the custom appointment.

@override
void initState() {
  _initializeEventColor();
  meetingQuery = fireBaseInstance
      .child("CalendarAppointmentCollection")
      .orderByChild('Subject');
  getDataFromDatabase().then((results) {
    setState(() {
      if (results != null) {
        querySnapshot = results;
        var collection = <Meeting>[];
 
        Map<dynamic, dynamic> values = querySnapshot.value;
        List<dynamic> key = values.keys.toList();
        if (values != null) {
          for (int i = 0; i < key.length; i++) {
            var data = values[key[i]];
            final Random random = new Random();
            collection.add(Meeting.map(
                data, _colorCollection[random.nextInt(9)], key[i]));
          }
        }
        events = _getCalendarDataSource(collection);
      }
    });
  });
  super.initState();
}
 
static Meeting map(dynamic data, Color color, String key) {
  return Meeting(
      eventName: data['Subject'],
      from: DateFormat('dd/MM/yyyy HH:mm:ss').parse(data['StartTime']),
      to: DateFormat('dd/MM/yyyy HH:mm:ss').parse(data['EndTime']),
      background: color,
      key: key,
      isAllDay: false);
}

STEP 4: Use onChildAdded, onChildRemoved, onChildChanged to notify the listeners of the Firebase database query. Flutter calendar can update its view by using notifyListeners with appropriate action.

onMeetingAdded(Event event) {
  if (!isInitialLoaded) {
    return;
  }
  if (event.snapshot.value != null) {
    final Random random = new Random();
    Meeting meeting = Meeting.fromSnapShot(
        event.snapshot, _colorCollection[random.nextInt(9)]);
    events.appointments.add(meeting);
    events.notifyListeners(CalendarDataSourceAction.add, [meeting]);
  }
}
 
onMeetingRemoved(Event event) {
  if (!isInitialLoaded) {
    return;
  }
  if (event.snapshot.value != null) {
    int index = events.appointments
        .indexWhere((element) => element.key == event.snapshot.key);
    Meeting meeting = events.appointments[index];
    events.appointments.remove(meeting);
    events.notifyListeners(CalendarDataSourceAction.remove, [meeting]);
  }
}
 
onMeetingChanged(Event event) {
  if (!isInitialLoaded) {
    return;
  }
  if (event.snapshot.value != null) {
    final Random random = new Random();
    Meeting meeting = Meeting.fromSnapShot(
        event.snapshot, _colorCollection[random.nextInt(9)]);
    events.appointments.remove(meeting);
    events.notifyListeners(CalendarDataSourceAction.remove, [meeting]);
    events.appointments.add(meeting);
    events.notifyListeners(CalendarDataSourceAction.add, [meeting]);
  }
}

View the GitHub sample here

Firebase CRUD

 

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Access denied
Access denied