I am using table_calendar flutter package to add a calendar with events. I need to declare a function that uses state from bloc. Is there any problem with his approach? Right now it's working but I feel like there is a better solution that I can't think of.
class TableView extends StatelessWidget {
const TableView({super.key});
@override
Widget build(BuildContext context) {
return BlocBuilder<CalendarBloc, CalendarState>(
builder: (context, state) {
List<Schedule> _getEventsForDay(DateTime day) {
final calendar = state.days.firstWhereOrNull(
(calendar) => day.isOnCalendar(calendar),
);
return calendar == null ? [] : calendar.schedules ?? [];
}
return TableCalendar<Schedule>(
focusedDay: state.focusedDay ?? DateTime.now(),
firstDay: kFirstDay,
lastDay: kLastDay,
selectedDayPredicate: (day) => isSameDay(state.selectedDay, day),
onDaySelected: (selectedDay, focusedDay) {
context.read<CalendarBloc>().add(
DaySelected(
selectedDay: selectedDay,
focusedDay: focusedDay,
),
);
},
eventLoader: _getEventsForDay,
// calendarFormat: CalendarFormat.month,
);
},
);
}
}
CodePudding user response:
Moving the _getEventsForDay
function into the CalendarBloc
is a good idea as it will make the code easier to test and maintain. The function can be a private method inside the CalendarBloc
class. This way, the business logic can be tested in isolation, which will make the tests more reliable and easier to write.
In addition, this also makes the code more modular and separates the presentation logic (the UI) from the business logic (the bloc).