Want to show events in Calendar Widget dynamically - flutter

I want to print the events from an event list that I'm getting from API. In this code, the events attribute of the Calendar widget is hardcoded. what should I do?
events Map(It's the Map of events that is getting passed on to the events attribute of calender, instead of this i want to pass my own list of events which im getting from API)
final Map<DateTime, List<CleanCalendarEvent>> events = {
DateTime(DateTime.now().year, DateTime.now().month, DateTime.now().day): [
CleanCalendarEvent('Event A',
startTime: DateTime(DateTime.now().year, DateTime.now().month,
DateTime.now().day + 1, 10, 0),
endTime: DateTime(DateTime.now().year, DateTime.now().month,
DateTime.now().day + 1, 12, 0),
description: 'A special event',
color: Colors.orangeAccent),
],
};
void _handleData(date) {
setState(() {
selectedDay = date;
selectedEvent = events[selectedDay] ?? [];
});
}
Calendar widget inside the body of Scaffold
Calendar(
startOnMonday: false,
selectedColor: Colors.blue,
todayColor: Colors.red,
eventColor: Colors.green,
eventDoneColor: Colors.amber,
bottomBarColor: Colors.deepOrange,
onRangeSelected: (range) {
print('selected Day ${range.from},${range.to}');
},
onDateSelected: (date) {
return _handleData(date);
},
events: events,
isExpanded: true,
dayOfWeekStyle: const TextStyle(
fontSize: 12,
color: Colors.blueGrey,
fontWeight: FontWeight.bold,
),
bottomBarTextStyle: const TextStyle(
color: Colors.white,
),
hideBottomBar: false,
hideArrows: false,
weekDays: const [
'Mon',
'Tue',
'Wed',
'Thu',
'Fri',
'Sat',
'Sun'
],
),

Related

flutter show totals on table calendar

I have a List of DatesAppointmentTotals object.
List<DatesAppointmentTotals> daTotals = [
DatesAppointmentTotals(appointmentDate: '2022/08/08', appointmentTotals: 25),
DatesAppointmentTotals(appointmentDate: '2022/08/09', appointmentTotals: 5),
DatesAppointmentTotals(appointmentDate: '2022/08/10', appointmentTotals: 12),
];
I want to show the appointmentTotals in the table calendar based on the appointmentDate, does anyone have an idea how to do this? Maybe I can add it on the markerbuilder...
body: TableCalendar(
calendarBuilders: CalendarBuilders(
markerBuilder: (context, datetime, events) {
return Container(
width: 48,
height: 15,
decoration: BoxDecoration(color: Colors.blue.shade600),
child: Text(
'24',
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.white,
fontSize: 10,
),
),
);
},
),
focusedDay: DateTime.now(),
firstDay: DateTime.now().subtract(Duration(days: 30)),
lastDay: DateTime.now().add(Duration(days: 90)),
calendarFormat: format,
onFormatChanged: (CalendarFormat _format) {
setState(
() {
format = _format;
},
);
},
onDaySelected: (DateTime selectDay, DateTime focusDay) {
setState(() {
selectedDay = selectDay;
focusedDay = focusDay;
showAppointments();
});
},
selectedDayPredicate: (DateTime date) {
return isSameDay(selectedDay, date);
},
isTodayHighlighted: true,
),

Problems adding events in Flutter Calendar

I am trying to make a simple calendar app in Flutter. He had no problems installing the dependencies, but when he tried to add events he couldn't. It used Date.Time.now with no problem, but when it tried to do it with a specific date it failed. I would appreciate someone who could help me. Thanks a lot
import 'package:flutter_clean_calendar/flutter_clean_calendar.dart';
class MoonCalendar extends StatefulWidget {
#override
_MoonCalendarState createState() => _MoonCalendarState();
}
class _MoonCalendarState extends State<MoonCalendar> {
DateTime selectedDay;
List <CleanCalendarEvent> selectedEvent;
final Map<DateTime,List<CleanCalendarEvent>> events = {
DateTime (DateTime.utc(2022).year,DateTime.utc(07).month,DateTime.utc(15).day):
[
CleanCalendarEvent(
'Event A',
startTime: DateTime(
DateTime.utc(2022).year,DateTime.utc(7).month,DateTime.utc(15).day,10,0),
endTime: DateTime(
DateTime.utc(2022).year,DateTime.utc(7).month,DateTime.utc(15).day,12,0),
description: 'A special event',
color: Colors.blue[700]),
],
};
void _handleData(date){
setState(() {
selectedDay = date;
selectedEvent = events[selectedDay] ?? [];
});
print(selectedDay);
}
#override
void initState() {
// TODO: implement initState
selectedEvent = events[selectedDay] ?? [];
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
"Calendario",
style: TextStyle(fontSize: 22),
),
Text(
" Lunar",
style: TextStyle(fontSize: 22, color: Color.fromRGBO(56, 215, 199, 1)),
)
],
),
),
body: SafeArea(
child: Container(
decoration: BoxDecoration(
gradient: const LinearGradient(
colors: [
Color.fromRGBO(61, 138, 146, 0.2),
Color.fromRGBO(56, 215, 199, 0.1)
]
)
),
child: Calendar(
startOnMonday: true,
selectedColor: Colors.blue,
todayColor: Colors.red,
eventColor: Colors.green,
eventDoneColor: Colors.amber,
bottomBarColor: Colors.deepOrange,
onRangeSelected: (range) {
print('selected Day ${range.from},${range.to}');
},
onDateSelected: (date){
return _handleData(date);
},
events: events,
isExpanded: true,
dayOfWeekStyle: TextStyle(
fontSize: 15,
color: Colors.black12,
fontWeight: FontWeight.w100,
),
bottomBarTextStyle: TextStyle(
color: Colors.black87,
),
hideBottomBar: false,
hideArrows: false,
weekDays: ['Lun','Mar','Mié','Jue','Vie','Sáb','Dom'],
),
),
),
);
}
} ```

How to display Map in dropdown flutter?

I need to implement a dropdown list in which you do not need to select items, but only view it. As an alternative, I decided to use the dropdown widget since I don't know any other options. I ran into a problem, I have a Map with data that needs to be displayed in a drop-down menu, how to do it correctly because it doesn’t work for me, I need to display both weeks and time (attached a screenshot below)? If you know of a better option than using dropdown for my purpose, I'd love to hear a suggestion.
code
class StatusDropdown extends StatefulWidget {
const StatusDropdown({Key? key}) : super(key: key);
#override
State<StatusDropdown> createState() => _StatusDropdown();
}
class _StatusDropdown extends State<StatusDropdown> {
String? selectedValue;
bool isChecked = false;
final Map<String, dynamic> items = {
'sun': '9:00-14:00',
'mon': '9:00-14:00',
'tus': '9:00-14:00',
'wed': 'Closed',
'thu': '00:00-24:00',
'fri': '9:00-14:00',
'sat': '9:00-14:00',
};
#override
Widget build(BuildContext context) {
return Container(
width: 141,
height: 28,
child: DropdownButtonHideUnderline(
child: DropdownButton2(
offset: const Offset(0, -12),
items: ...,
),
),
);
}
}
As per your result screen I have tried it using List instead of Map hope its help to you.
you must used dropdown_below from here
Create your list:
List dayTime = [
{'day': 'sun', 'time': '9:00-14:00'},
{'day': 'mon', 'time': '9:00-14:00'},
{'day': 'tus', 'time': '9:00-14:00'},
{'day': 'wed', 'time': 'Closed'},
{'day': 'thu', 'time': '00:00-24:00'},
{'day': 'fri', 'time': '9:00-14:00'},
{'day': 'sat', 'time': '9:00-14:00'},
];
One varibale and list our value
List<DropdownMenuItem<Object?>> _dropdownTestItems = [];
var selectedDayTime;
Create initState() and dispose() method:
#override
void initState() {
_dropdownTestItems = buildDropdownTestItems(dayTime);
super.initState();
}
#override
void dispose() {
super.dispose();
}
Add your selected number value in dropdown
List<DropdownMenuItem<Object?>> buildDropdownTestItems(List dayTime) {
List<DropdownMenuItem<Object?>> items = [];
for (var i in dayTime) {
items.add(
DropdownMenuItem(
value: i,
child: Text(
i['day'].toString() + '\t:\t' + i['time'].toString(),
style: TextStyle(color: Colors.black),
),
),
);
}
return items;
}
Your Widget:
Container(
color: Colors.white,
padding: const EdgeInsets.all(8.0),
child: DropdownBelow(
itemWidth: 150,
itemTextstyle: const TextStyle(
fontSize: 14, fontWeight: FontWeight.w400, color: Colors.black),
boxTextstyle: const TextStyle(
fontSize: 14,
fontWeight: FontWeight.w400,
color: Colors.white54),
boxPadding: EdgeInsets.fromLTRB(13, 12, 13, 12),
boxWidth: 150,
boxHeight: 45,
boxDecoration: BoxDecoration(
color: Colors.transparent,
border: Border.all(
width: 1,
color: Colors.black,
),
),
icon: Icon(
Icons.arrow_downward,
color: Colors.black,
),
hint: Text(
'Select Time',
style: TextStyle(
color: Colors.black,
),
),
value: selectedDayTime,
items: _dropdownTestItems,
onChanged: (selectedTest) {
setState(() {
selectedDayTime = selectedTest;
});
},
),
),
Your Dropdown button->
Your Dropdown data->
You can refer my same answer here and here, If you put map so refer this answer

how to get only date from the TableCalendar

I want to get only selected date from tablecalender, but it gives me this output
2021-08-18 12:00:00.000Z
here is tablecalender code
final dateFormat = DateFormat('yyyy-MMMM-dd');
DateTime _chosenDate = DateTime.now();
child: TableCalendar(
calendarController: _controller,
initialSelectedDay: _chosenDate,
initialCalendarFormat: CalendarFormat.month,
calendarStyle: CalendarStyle(
canEventMarkersOverflow: true,
markersColor: Colors.white,
weekdayStyle: TextStyle(color: Colors.blue[900]),
todayColor: Colors.white54,
todayStyle: TextStyle(color: Colors.blue[900], fontSize: 15, fontWeight: FontWeight.bold),
selectedColor: Colors.blue[900],
outsideWeekendStyle: TextStyle(color: Colors.blue[900]),
outsideStyle: TextStyle(color: Colors.blue[900]),
weekendStyle: TextStyle(color: Colors.blue[900]),
renderDaysOfWeek: false,),
onCalendarCreated: (date,event,_){
},
onDaySelected: (date, event,_) {
setState(() {
_chosenDate = date;
print("_chosenDate");
print(_chosenDate);
});
},
));
}
i tried to use split method, but it is not accessible
please help how to get only date (2021-08-18) using tablecalender
in print replace _chosenDate with "${_chosenDate.toString().split(" ").first}"

flutter - make dynamic mark event in calendar plugin

I want to mark the event once every 4 days.
example today is the 1st, mark the event will be available on the 5th, 10th, 15th, 20th, 25th, 30th, etc.
if today is the 3rd, the event will be available on the 8th, 13th, 18th, etc.
how does that function work?
I use this calendar plugin
https://pub.dev/packages/flutter_calendar_carousel
Following is the function to mark event manually:
EventList<Event> _markedDateMap = new EventList<Event>();
build(){
_calendarCarouselNoHeader = CalendarCarousel<Event>(
...
markedDatesMap: _markedDateMap,
...
),
}
#override
void initState() {
_markedDateMap.add(
new DateTime(2020, 2, 26),
new Event(
date: new DateTime(2020, 2, 26),
title: 'Event 5',
icon: _eventIcon,
));
_markedDateMap.add(
new DateTime(2020, 2, 26),
new Event(
date: new DateTime(2020, 2, 26),
title: 'Event 5',
icon: _eventIcon,
));
super.initState();
}
Any anwser will appreciated.
You can copy paste run full code below
working demo show when pass start date time with
addMarker(DateTime(2020, 2, 01));
addMarker(DateTime(2020, 2, 03));
code snippet
addMarker(DateTime startEventDateTime) {
var eventDateTime = startEventDateTime;
for(int i=0; i<5; i++) {
if(eventDateTime.day == 1) {
eventDateTime = eventDateTime.add(Duration(days: (4)));
} else {
eventDateTime = eventDateTime.add(Duration(days: (5)));
}
print(eventDateTime.toLocal());
_markedDateMap.add(
eventDateTime,
Event(
date: eventDateTime,
title: 'Event $i',
icon: _eventIcon,
));
}
}
working demo
full code
import 'package:flutter/material.dart';
import 'package:flutter_calendar_carousel/flutter_calendar_carousel.dart'
show CalendarCarousel;
import 'package:flutter_calendar_carousel/classes/event.dart';
import 'package:flutter_calendar_carousel/classes/event_list.dart';
import 'package:intl/intl.dart' show DateFormat;
void main() => runApp( MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'dooboolab flutter calendar',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Calendar Carousel Example'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
DateTime _currentDate = DateTime(2020, 2, 17);
DateTime _currentDate2 = DateTime(2020, 2, 17);
String _currentMonth = DateFormat.yMMM().format(DateTime(2020, 2, 17));
DateTime _targetDateTime = DateTime(2020, 2, 17);
// List<DateTime> _markedDate = [DateTime(2018, 9, 20), DateTime(2018, 10, 11)];
static Widget _eventIcon = Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.all(Radius.circular(1000)),
border: Border.all(color: Colors.blue, width: 2.0)),
child: Icon(
Icons.person,
color: Colors.amber,
),
);
EventList<Event> _markedDateMap = EventList<Event>();
CalendarCarousel _calendarCarousel, _calendarCarouselNoHeader;
#override
void initState() {
addMarker(DateTime(2020, 2, 03));
super.initState();
}
addMarker(DateTime startEventDateTime) {
var eventDateTime = startEventDateTime;
for(int i=0; i<5; i++) {
if(eventDateTime.day == 1) {
eventDateTime = eventDateTime.add(Duration(days: (4)));
} else {
eventDateTime = eventDateTime.add(Duration(days: (5)));
}
print(eventDateTime.toLocal());
_markedDateMap.add(
eventDateTime,
Event(
date: eventDateTime,
title: 'Event $i',
icon: _eventIcon,
));
}
}
#override
Widget build(BuildContext context) {
/// Example with custom icon
_calendarCarousel = CalendarCarousel<Event>(
onDayPressed: (DateTime date, List<Event> events) {
this.setState(() => _currentDate = date);
events.forEach((event) => print(event.title));
},
weekendTextStyle: TextStyle(
color: Colors.red,
),
thisMonthDayBorderColor: Colors.grey,
// weekDays: null, /// for pass null when you do not want to render weekDays
headerText: 'Custom Header',
// markedDates: _markedDate,
weekFormat: true,
markedDatesMap: _markedDateMap,
height: 200.0,
selectedDateTime: _currentDate2,
showIconBehindDayText: true,
// daysHaveCircularBorder: false, /// null for not rendering any border, true for circular border, false for rectangular border
customGridViewPhysics: NeverScrollableScrollPhysics(),
markedDateShowIcon: true,
markedDateIconMaxShown: 2,
selectedDayTextStyle: TextStyle(
color: Colors.yellow,
),
todayTextStyle: TextStyle(
color: Colors.blue,
),
markedDateIconBuilder: (event) {
return event.icon;
},
minSelectedDate: _currentDate.subtract(Duration(days: 360)),
maxSelectedDate: _currentDate.add(Duration(days: 360)),
todayButtonColor: Colors.transparent,
todayBorderColor: Colors.green,
markedDateMoreShowTotal:
false, // null for not showing hidden events indicator
// markedDateIconMargin: 9,
// markedDateIconOffset: 3,
);
/// Example Calendar Carousel without header and custom prev & next button
_calendarCarouselNoHeader = CalendarCarousel<Event>(
todayBorderColor: Colors.green,
onDayPressed: (DateTime date, List<Event> events) {
this.setState(() => _currentDate2 = date);
events.forEach((event) => print(event.title));
},
daysHaveCircularBorder: true,
showOnlyCurrentMonthDate: false,
weekendTextStyle: TextStyle(
color: Colors.red,
),
thisMonthDayBorderColor: Colors.grey,
weekFormat: false,
// firstDayOfWeek: 4,
markedDatesMap: _markedDateMap,
height: 420.0,
selectedDateTime: _currentDate2,
targetDateTime: _targetDateTime,
customGridViewPhysics: NeverScrollableScrollPhysics(),
markedDateCustomShapeBorder: CircleBorder(
side: BorderSide(color: Colors.yellow)
),
markedDateCustomTextStyle: TextStyle(
fontSize: 18,
color: Colors.blue,
),
showHeader: false,
// markedDateIconBuilder: (event) {
// return Container(
// color: Colors.blue,
// );
// },
todayTextStyle: TextStyle(
color: Colors.blue,
),
todayButtonColor: Colors.yellow,
selectedDayTextStyle: TextStyle(
color: Colors.yellow,
),
minSelectedDate: _currentDate.subtract(Duration(days: 360)),
maxSelectedDate: _currentDate.add(Duration(days: 360)),
prevDaysTextStyle: TextStyle(
fontSize: 16,
color: Colors.pinkAccent,
),
inactiveDaysTextStyle: TextStyle(
color: Colors.tealAccent,
fontSize: 16,
),
onCalendarChanged: (DateTime date) {
this.setState(() {
_targetDateTime = date;
_currentMonth = DateFormat.yMMM().format(_targetDateTime);
});
},
onDayLongPressed: (DateTime date) {
print('long pressed date $date');
},
);
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
//custom icon
Container(
margin: EdgeInsets.symmetric(horizontal: 16.0),
child: _calendarCarousel,
), // This trailing comma makes auto-formatting nicer for build methods.
//custom icon without header
Container(
margin: EdgeInsets.only(
top: 30.0,
bottom: 16.0,
left: 16.0,
right: 16.0,
),
child: Row(
children: <Widget>[
Expanded(
child: Text(
_currentMonth,
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 24.0,
),
)),
FlatButton(
child: Text('PREV'),
onPressed: () {
setState(() {
_targetDateTime = DateTime(_targetDateTime.year, _targetDateTime.month -1);
_currentMonth = DateFormat.yMMM().format(_targetDateTime);
});
},
),
FlatButton(
child: Text('NEXT'),
onPressed: () {
setState(() {
_targetDateTime = DateTime(_targetDateTime.year, _targetDateTime.month +1);
_currentMonth = DateFormat.yMMM().format(_targetDateTime);
});
},
)
],
),
),
Container(
margin: EdgeInsets.symmetric(horizontal: 16.0),
child: _calendarCarouselNoHeader,
), //
],
),
));
}
}