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
Please  to leave a comment
Access denied
Access denied