Articles in this section
Category / Section

How to work on Firebase database in Flutter Calendar for appointment?

5 mins read

In the Flutter Event Calendar, you can add the appointment data to FireBase database from selected value of PopupMenuItem and fetch these values to display as 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. Please refer the following   Firebase documentation to create database and store the data.

Firebase data

STEP 3: Add a method for fetching data from the 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 update appointment values.

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

STEP 5: Fetch 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 to add appointment data to the database based on the selected value from the PopupMenuItem. The push() method creates a random ID in the database, and the set() method contains the data from the form. The then() callback executes after the data is added to the Firebase database. You can also use the remove() method to delete data from 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 the GitHub sample here

Flutter firebase data with resource

Conclusion

I hope you enjoyed learning how to work with Firebase database in Flutter Calendar for appointment.

You can refer to our Flutter Calendar feature tour page to know about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications.

For current customers, you can check out our components from the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our other controls.

If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forumsDirect-Trac, or feedback portal. We are always happy to assist you!



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