How to deselected a day on calendar

78 Views Asked by At

I am creating a custom calendar with TableCalendar package, when I selected day 14 on calendar, Function selectedBuilder will rebuild a widget with black thicker size border, and I selected the same day 14 again, will deselected day and remove black thicker border on day 14, But I don't know how to deselect day of calendar. How can I do this?

This is my UI

1

There are 1 best solutions below

0
Dharam Budh On

In the below-written code, the focusedDay has been set as the current day (Today). If you pick any other date, then the marker will update accordingly. But if you select the same date twice / tap it twice, it will roll back to the initial day (Today). So, when we want to de-select it, we tap on it again & it'll reset.

Source code:

import "package:flutter/material.dart";
import "package:table_calendar/table_calendar.dart";

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(home: MyWidget());
  }
}

class MyWidget extends StatefulWidget {
  const MyWidget({super.key});

  @override
  State<MyWidget> createState() => _MyWidgetState();
}

class _MyWidgetState extends State<MyWidget> {
  DateTime focusedDay = DateTime.now();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: Column(
          children: <Widget>[
            TableCalendar<DateTime>(
              firstDay: DateTime.utc(2010, 10, 16),
              lastDay: DateTime.utc(2030, 3, 14),
              focusedDay: focusedDay,
              selectedDayPredicate: (DateTime dt) => isSameDay(focusedDay, dt),
              onDaySelected: (DateTime selected, DateTime focused) {
                focusedDay = (focusedDay == focused) ? DateTime.now() : focused;
                setState(() {});
              },
            ),
          ],
        ),
      ),
    );
  }
}