Display Dynamic Events At Calendar In Flutter
Flutter has been a magnificent experience from the very beginning. Building gorgeous UI had never been quicker. It’s easy to fall in love with Flutter, regardless of whether you’re a beginner or an accomplished developer. All software developers realize that dates are the trickiest thing. What’s more, calendars are no exception.
A lot of these libraries are as yet under active development. Likewise, because a library can’t play out the entirety of the challenge calendar’s prerequisites doesn’t make it a more fragile library. Each calendar has various requirements!
In this blog, we will explore the Display Dynamic Events At Calendar In Flutter. We will also implement a demo program, display and create dynamic events on the calendar using the table_calendar package in your flutter applications.
table_calendar | Flutter Package
Highly customizable, feature-packed Flutter Calendar with gestures, animations, and multiple formats. Table Calendar…pub. dev
Table Of Contents::
Flutter Calendar:
A calendar is a framework used to arrange the days, weeks, or months for business, religious, social, or regulatory purposes. It tracks which events fall on a specific date and when the special events will occur.
Flutter gives a basic plugin named table_calendar to show the calendar in our application. The table calendar is exceptionally adjustable and has numerous features, for example, gesture, animation, and various configurations.
Demo Module ::
In this screenshot of the demo, we will add events on a particular date using the table_calendar package and use shared preference to store events in your flutter application.
Features:
- > It is easy to use API.
- > It provides Dynamic events.
- > It provides Custom Builders for UI control.
- > It has vertical auto-sizing.
- > It provides beautiful animations.
- > It provides gesture handling.
- > It provides multiple calendar formats such as a month, weak, year, etc.
- > We can also use multiple days of the week formats.
Implementation:
Step 1: Add the dependencies
Add dependencies to pubspec — yaml file.
dependencies:
table_calendar:
shared_preferences:
Step 2: Import
import 'package:table_calendar/table_calendar.dart';
import 'package:shared_preferences/shared_preferences.dart';
Step 3: Run flutter packages get in the root directory of your app.
Step 4: Enable AndriodX
Add this to your gradle.properties file:
org.gradle.jvmargs=-Xmx1536M
android.enableR8=true
android.useAndroidX=true
android.enableJetifier=true
How to implement code in dart file :
You need to implement it in your code respectively:
Create a new dart file called dynamic_event.dart
inside the lib
folder.
In the TableCalendar, all data are required; we will deeply describe below the code. We will set a calendar format is week.
CalendarStyle(
canEventMarkersOverflow: true,
todayColor: Colors.orange,
selectedColor: Theme.of(context).primaryColor,
todayStyle: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 18.0,
color: Colors.white)),
In the CalendarStyle, we will add current date color and selected color for users easily identified, and users can change text color according to your applications.
HeaderStyle(
centerHeaderTitle: true,
formatButtonDecoration: BoxDecoration(
color: Colors.orange,
borderRadius: BorderRadius.circular(20.0),
),
formatButtonTextStyle: TextStyle(color: Colors.white),
formatButtonShowsNext: false,
),
In the HeaderStyle, we will center the header title and create a formatButtonDecoration for a month, week, year, etc., and color on it.
CalendarBuilders(
selectedDayBuilder: (context, date, events) => Container(
margin: const EdgeInsets.all(4.0),
alignment: Alignment.center,
decoration: BoxDecoration(
color: Theme.of(context).primaryColor,
borderRadius: BorderRadius.circular(10.0)),
child: Text(
date.day.toString(),
style: TextStyle(color: Colors.white),
)),
todayDayBuilder: (context, date, events) => Container(
margin: const EdgeInsets.all(4.0),
alignment: Alignment.center,
decoration: BoxDecoration(
color: Colors.orange,
borderRadius: BorderRadius.circular(10.0)),
child: Text(
date.day.toString(),
style: TextStyle(color: Colors.white),
)),
),
In the CalendarBuilders, we will add two builders that were selectedDayBuilder and todayDayBuilder. In selectedDayBuilder, we will add a container for the selected date, text, add color. In todayDayBuilder, we will add the same container, but the color was changed for the user to be identified for the current date.
First, let us create a variables that keeps our events interval calendar
Map<DateTime, List<dynamic>> _events;
List<dynamic> _selectedEvents;
Event is a map of key DateTime and lists the dynamic list of where this list is the list of events for that day. Create another variable list dynamic for selected events. Both variables will be initialized on initState().
@override
void initState() {
super.initState();
_events = {};
_selectedEvents = [];
}
In TableCalendar, let us assign events as underscore events. Whenever the day is selected, set state, so interval calendar on the day selected property.
onDaySelected: (date, events,holidays) {
setState(() {
_selectedEvents = events;
});
},
We will add a floating action button in our scaffold that will allow us to load the dialog from which we can add events to the selected date.
floatingActionButton: FloatingActionButton(
backgroundColor: Colors.black,
child: Icon(Icons.add),
onPressed: _showAddDialog,
),
Let’s create a method _showAddDialog().
_showAddDialog() async {
await showDialog(
context: context,
builder: (context) => AlertDialog(
backgroundColor: Colors.white70,
title: Text("Add Events"),
content: TextField(
controller: _eventController,
),
actions: <Widget>[
FlatButton(
child: Text("Save",style: TextStyle(color: Colors.red,fontWeight: FontWeight.bold),),
onPressed: () {
if (_eventController.text.isEmpty) return;
setState(() {
if (_events[_controller.selectedDay] != null) {
_events[_controller.selectedDay]
.add(_eventController.text);
} else {
_events[_controller.selectedDay] = [
_eventController.text
];
}
_eventController.clear();
Navigator.pop(context);
});
},
)
],
));
}
In this dialog, we will add a title, textField, and flat button. In the button onPressed() method, if the underscore event controller the text is empty, then return. If not underscore events so, first we check if on the square events, so our controller is a table calendar controller dot selected day if this is not equal to null then add underscore events in square bracket controller dot selected day dot to add event controller text so we’ll add a new event else if that is null then we need to create that object is controller dot selected day is equal to the event controller text. Let us wrap this always in setState().
..._selectedEvents.map((event) => Padding(
padding: const EdgeInsets.all(8.0),
child: Container(
height: MediaQuery.of(context).size.height/20,
width: MediaQuery.of(context).size.width/2,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(30),
color: Colors.white,
border: Border.all(color: Colors.grey)
),
child: Center(
child: Text(event,
style: TextStyle(color: Colors.blue,
fontWeight: FontWeight.bold,fontSize: 16),)
),
),
)),
After TableCalendar inside the column, let us use this for selected events dot map(). We will use container and child property; we will add text events. When we run the application, we ought to get the screen’s output like the underneath video capture.
This video shows how to select a date and then click on the floating action button. A dialog box opens; we will add an event and then save the events. Also, we will add multiple events. The event name will be displayed on our devices. We will not add shared preferences.
Now, We will add shared preferences.
SharedPreferences prefs;
First, we will be called SharePrences as prefs and then initialize to initState().
@override
void initState() {
super.initState();
prefsData();
}
I have also added two functions, helper functions that help to encode and decode our events map, so this will help us covert our events map into a string that we can save to sharedPreference and load it from sharedPreference.
Map<String, dynamic> encodeMap(Map<DateTime, dynamic> map) {
Map<String, dynamic> newMap = {};
map.forEach((key, value) {
newMap[key.toString()] = map[key];
});
return newMap;
}
Map<DateTime, dynamic> decodeMap(Map<String, dynamic> map) {
Map<DateTime, dynamic> newMap = {};
map.forEach((key, value) {
newMap[DateTime.parse(key)] = map[key];
});
return newMap;
}
Let’s define prefsData() function.
First, prefs is equal to SharedPreferences.getInstance(). Underscore events are equal to the map dot from decodeMap.In decodeMap, json dot decode and prefs.getString(“events”), and if this is null, then we pass an empty map integer string.
prefsData() async {
prefs = await SharedPreferences.getInstance();
setState(() {
_events = Map<DateTime, List<dynamic>>.from(
decodeMap(json.decode(prefs.getString("events") ?? "{}")));
});
}
Now, we will add a dialog box onPressed() method, and whenever we add new events, we’d like to save those to the sharePreference.
prefs.setString("events", json.encode(encodeMap(_events)));
When we run the application, we ought to get the screen’s output like the underneath video capture.
This video shows how to select a date and then click on the floating button. A dialog box opens; we will add the event and then save the events. Also, we will add multiple events. The event name will be displayed on our devices. When hot restart so these events should be persisted and loaded from sharePreference, you can see the events marker, and if we press here if we select the dates, we can see those events on our devices.
Code File:
https://gist.github.com/ShaiqAhmedkhan/b859609c91d8df5ed92fa506e2126bf8#file-dynamic_events-dart
Conclusion:
In the article, I have explained the basic structure of the Display Dynamic Events At Calendar in a flutter; you can modify this code according to your choice. This was a small introduction to Display Dynamic Events At Calendar On User Interaction from my side, and it’s working using Flutter.
I hope this blog will provide you with sufficient information in Trying up the Display Dynamic Events At Calendar in your flutter projects. We will show you the flutter calendar, some features, and show how to display and create dynamic events on the calendar using the table_calendar package and store the events on sharePreferences in your flutter applications, So please try it.
❤ ❤ Thanks for reading this article ❤❤https://giphy.com/embed/lD76yTC5zxZPG/twitter/iframe
If I got something wrong? Let me know in the comments. I would love to improve.
Clap 👏 If this article helps you.
find the source code of the Flutter Dynamic Event Calendar Demo:
flutter-devs/flutter_dynamic_event_calendar_demo
A new Flutter application. This project is a starting point for a Flutter application. A few resources to get you…github.com
Feel free to connect with us:
And read more articles from FlutterDevs.com.
FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire a flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! You can connect with us on Facebook, GitHub, Twitter, and LinkedIn for any flutter-related queries.
We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences.