How to perform the CRUD operations in Flutter Calendar using Firestore database
In the Flutter Event Calendar, perform the CRUD operation on the appointments using the Firestore database.
Refer to the following guidelines to create the Firestore database.
https://firebase.google.com/docs/firestore/quickstart
Refer to the following article, to add the appointments to Firestore database and to show the same in the Flutter calendar.
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
STEP 2: Fetch the data from the created firestore.
Future<void> getDataFromFireStore() async { var snapShotsValue = await fireStoreReference .collection("CalendarAppointmentCollection") .get(); final Random random = new Random(); List<Meeting> list = snapShotsValue.docs .map((e) => Meeting( eventName: e.data()['Subject'], from: DateFormat('dd/MM/yyyy HH:mm:ss').parse(e.data()['StartTime']), to: DateFormat('dd/MM/yyyy HH:mm:ss').parse(e.data()['EndTime']), background: _colorCollection[random.nextInt(9)], isAllDay: false, key: e.id)) .toList(); setState(() { events = MeetingDataSource(list); }); }
STEP 3: In initState() populate the appointments from the Firestore database, using the fetched result.
void initState() { _initializeEventColor(); getDataFromFireStore().then((results) { SchedulerBinding.instance!.addPostFrameCallback((timeStamp) { setState(() {}); }); });
STEP 4: Using the listen() method, fetchyou can get the notifications of the document changes s such as added, removed, and changed. Then based on the DocumentChangeType Flutter calendar can update its view by using the notifyListeners with an appropriate action.
fireStoreReference .collection("CalendarAppointmentCollection") .snapshots() .listen((event) { event.docChanges.forEach((element) { if (element.type == DocumentChangeType.added) { if (!isInitialLoaded) { return; } final Random random = new Random(); Meeting app = Meeting.fromFireBaseSnapShotData(element, _colorCollection[random.nextInt(9)]); setState(() { events!.appointments!.add(app); events!.notifyListeners(CalendarDataSourceAction.add, [app]); }); } else if (element.type == DocumentChangeType.modified) { if (!isInitialLoaded) { return; } final Random random = new Random(); Meeting app = Meeting.fromFireBaseSnapShotData(element, _colorCollection[random.nextInt(9)]); setState(() { int index = events!.appointments! .indexWhere((app) => app.key == element.doc.id); Meeting meeting = events!.appointments![index]; events!.appointments!.remove(meeting); events!.notifyListeners(CalendarDataSourceAction.remove, [meeting]); events!.appointments!.add(app); events!.notifyListeners(CalendarDataSourceAction.add, [app]); }); } else if (element.type == DocumentChangeType.removed) { if (!isInitialLoaded) { return; } setState(() { int index = events!.appointments! .indexWhere((app) => app.key == element.doc.id); Meeting meeting = events!.appointments![index]; events!.appointments!.remove(meeting); events!.notifyListeners(CalendarDataSourceAction.remove, [meeting]); }); } }); static Meeting fromFireBaseSnapShotData(dynamic element, Color color) { return Meeting( eventName: element.doc.data()!['Subject'],, from: DateFormat('dd/MM/yyyy HH:mm:ss') .parse(element.doc.data()!['StartTime']), to: DateFormat('dd/MM/yyyy HH:mm:ss') .parse(element.doc.data()!['EndTime']), background: color, isAllDay: false, key: element.doc.id); }
STEP 5: Add the appointment data to the Firestore using the PopupMenuItem and assign the events to the dataSource property.
appBar: AppBar( 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') { fireStoreReference .collection("CalendarAppointmentCollection") .doc("1") .set({ 'Subject': 'Mastering Flutter', 'StartTime': '07/04/2020 08:00:00', 'EndTime': '07/04/2020 09:00:00' }); } else if (value == "Delete") { try { fireStoreReference .collection('CalendarAppointmentCollection') .doc('1') .delete(); } catch (e) {} } else if (value == "Update") { try { fireStoreReference .collection('CalendarAppointmentCollection') .doc('1') .update({'Subject': 'Meeting'}); } catch (e) {} } },, )),