简体   繁体   English

我可以在 flutter_bloc 构建器中声明一个 function 吗?

[英]Can I declare a function inside a flutter_bloc builder?

I am using table_calendar flutter package to add a calendar with events.我正在使用table_calendar flutter package 添加带有事件的日历。 I need to declare a function that uses state from bloc.我需要声明一个 function,它使用来自 bloc 的 state。 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,
        );
      },
    );
  }
}

Moving the _getEventsForDay function into the CalendarBloc is a good idea as it will make the code easier to test and maintain._getEventsForDay function 移动到CalendarBloc是一个好主意,因为它会使代码更易于测试和维护。 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. function可以是CalendarBloc class内部的私有方法。这样可以隔离测试业务逻辑,使测试更可靠,更容易编写。

In addition, this also makes the code more modular and separates the presentation logic (the UI) from the business logic (the bloc).此外,这也使代码更加模块化,并将表示逻辑(UI)与业务逻辑(bloc)分开。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM