Home > Software engineering >  onFormatChanged() not working with TableCalendar
onFormatChanged() not working with TableCalendar

Time:08-04

fI wrote the onFormatChanged() method and set the property, but when I use the button on the calendar to change the format, I do not see anything happen. Is there anything I'm doing wrong?

class Calendar extends StatefulWidget {
  const Calendar({Key? key}) : super(key: key);

  @override
  State<Calendar> createState() => _CalendarState();
}

class _CalendarState extends State<Calendar> {
  @override
  Widget build(BuildContext context) {
    double heigth_sc = MediaQuery.of(context).size.height;
    double width_sc = MediaQuery.of(context).size.width;
    CalendarFormat _calendarFormat = CalendarFormat.month;

    return Scaffold(
        appBar: PreferredSize(
            preferredSize: Size.fromHeight(heigth_sc * 0.10),
            child: AppBar(
                centerTitle: true,
                title: const Text("Calendar"),
        body: TableCalendar(
          focusedDay: DateTime.now(),
          firstDay: DateTime(2017),
          lastDay: DateTime(2117),
          calendarFormat: _calendarFormat,
          onFormatChanged: (format) {
            if (_calendarFormat != format) {
              // Call `setState()` when updating calendar format
              setState(() {
                _calendarFormat = format;
              });
            }
          },
        ),
    );
  }
}

CodePudding user response:

Put _calendarFormat outside the build method

  CalendarFormat _calendarFormat = CalendarFormat.month;

  @override
  Widget build(BuildContext context) {
    double heigth_sc = MediaQuery.of(context).size.height;
    double width_sc = MediaQuery.of(context).size.width;
  • Related