Kanesha Mallory
Kanesha Mallory

Reputation: 35

Add listener with Table Calendar Flutter

Hi I'm new to Flutter (and to coding in particular) and I'm trying to make a calendar with table_calendar. I'm searching for a way to have a start and end date on my events (which are saved in Firebase). The OnDaySelected function built into the widget doesn't seem to work for this but I think the solution would be to add a listener to the _controller.selectedDay so that every time I click on a date I can call a specific function.

I've tried Value Notifier but it is called on null and I can't figure out why. I can use _controller.selectedDay to pass the date to the AddSchedule page so I'm not sure why the value on the actual calendar wouldn't be able to show up. Am I implementing ValueNotifier wrong or is there any other way to do this?

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(...),
          ),
        ),
      ),
    );
  }

Upvotes: 0

Views: 1374

Answers (1)

user14736790
user14736790

Reputation:

You can use onDaySelected with a setState to change the variable content

onDaySelected: (date, events, _){
    setState(() {
       _thisDay = date;
    });
},

Upvotes: 1

Related Questions