Добавить слушателя с Table Calendar Flutter

Привет, я новичок во Flutter (и, в частности, в кодировании), и я пытаюсь создать календарь с помощью table_calendar < / а>. Я ищу способ указать дату начала и окончания моих событий (которые сохраняются в Firebase). Функция OnDaySelected, встроенная в виджет, похоже, не работает для этого, но я думаю, что решением было бы добавить слушателя к _controller.selectedDay, чтобы каждый раз, когда я нажимаю на дату, я мог вызывать определенную функцию.

Я пробовал Value Notifier, но он вызывается с нулевым значением, и я не могу понять, почему. Я могу использовать _controller.selectedDay для передачи даты на страницу AddSchedule, поэтому я не уверен, почему значение в реальном календаре не может отображаться. Я неправильно использую ValueNotifier или есть другой способ сделать это?

class SchedulePage extends StatefulWidget { @override _SchedulePageState createState() => _SchedulePageState(); } class _SchedulePageState extends State<SchedulePage> { CalendarController _controller; List routes = []; List locations = []; List distinctLocations = []; List filter = []; List lastFilter = []; List selectedEvents = []; var daySelect; @override void initState() { super.initState(); getRoutes(); _controller = CalendarController(); daySelect = ValueNotifier<DateTime>(_controller.selectedDay); daySelect.value.notifyListeners(); } @override void dispose() { _controller.dispose(); super.dispose(); } getRoutes() async { final data = await FirebaseFirestore.instance .collection(«Routes») .orderBy(«driver») .get(); List routeList = List(); for (int i = 0; i < data.docs.length; i++) { routeList.add(data.docs[i]); } routes = routeList; filter = routes .where((element) => element[‘startDate’].toDate().isBefore(_controller.selectedDay) && element[‘endDate’].toDate().isAfter(_controller.selectedDay)).toList(); locations = filter.map((element) => element[«locationName»].toString()).toList(); distinctLocations = locations.toSet().toList(); setState(() {}); } getFilter(DateTime day) { filter = routes .where((element) => element[‘startDate’].toDate().isBefore(day) && element[‘endDate’].toDate().isAfter(day)).toList(); locations = filter.map((element) => element[«locationName»].toString()).toList(); distinctLocations = locations.toSet().toList(); } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.grey[900], appBar: AppBar(…), body: SingleChildScrollView( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Container( height: 210, decoration: BoxDecoration(color: Colors.grey[900], boxShadow: [ BoxShadow( color: Colors.black.withOpacity(0.8), blurRadius: 10.0, offset: Offset(0, 10), ), ]), child: TableCalendar( calendarController: _controller, initialCalendarFormat: CalendarFormat.twoWeeks, calendarStyle: CalendarStyle( todayColor: Colors.red.withOpacity(0.7), selectedColor: Color(0xFFF00F12), weekendStyle: TextStyle( color: Colors.red, fontWeight: FontWeight.w600), markersColor: Colors.white, markersMaxAmount: 1, weekdayStyle: TextStyle( color: Colors.white, fontWeight: FontWeight.w600)), daysOfWeekStyle: DaysOfWeekStyle( weekdayStyle: TextStyle( color: Colors.white.withOpacity(0.5), fontWeight: FontWeight.w600), ), headerStyle: HeaderStyle( formatButtonVisible: false, centerHeaderTitle: true, titleTextStyle: TextStyle( color: Colors.red, fontSize: 19.0, ), leftChevronIcon: Icon(Icons.chevron_left, color: Colors.white), rightChevronIcon: Icon( Icons.chevron_right, color: Colors.white, )), ), ), SingleChildScrollView( child: Container( height: 800, color: Colors.black38, child: ValueListenableBuilder( valueListenable: daySelect, builder: (context, n, c){ return FutureBuilder( future: getFilter(daySelect.value), builder: (context, w) { if(!w.hasData) { return _buildSchedule(); } else { return Center( child: CircularProgressIndicator( backgroundColor: Colors.white, )); } }); }, ), ), ), ], ), ), floatingActionButton: Container( height: 45, width: 45, child: FittedBox( child: FloatingActionButton( backgroundColor: Colors.white, onPressed: () { Navigator.of(context).push(MaterialPageRoute(builder: (_) { return addSchedule(_controller.selectedDay); })); }, child: Text(…), ), ), ), ); }

Я не понял, что именно вы хотите. Хотите получить начальный и последний дни текущего календаря?   —  person Kanesha Mallory    schedule 26.02.2021

Нет, я хочу добавить слушателя к selectedDay в календаре. Скажем, я нажимаю 1 марта в календаре, я хочу, чтобы слушатель показывал этот результат и выполнял функцию, когда я нажимаю на новую дату.   —  person Kanesha Mallory    schedule 26.02.2021

Подождите минутку .   —  person Kanesha Mallory    schedule 26.02.2021

Источник: ledsshop.ru

Стиль жизни - Здоровье!