1.添加table_calendar库

table_calendar库当前最新版本为3.1.0

pubspec.yaml添加依赖3.1.0

1
2
dependencies:
  table_calendar: ^3.1.0

2.table_calendar简单使用

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import 'package:base_demo/common/logger.dart';
import 'package:flutter/material.dart';
import 'package:table_calendar/table_calendar.dart';

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

  @override
  // ignore: library_private_types_in_public_api
  CalendarScreenPageState createState() => CalendarScreenPageState();
}

class CalendarScreenPageState extends State<CalendarScreenPage> {
  CalendarFormat _calendarFormat = CalendarFormat.month;
  DateTime _focusedDay = DateTime.now();
  DateTime _selectedDay = DateTime.now();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Calendar Selector'),
      ),
      body: TableCalendar(
        firstDay: DateTime.utc(2010, 1, 1),
        lastDay: DateTime.utc(2030, 1, 1),
        focusedDay: _focusedDay,
        calendarFormat: _calendarFormat,

        selectedDayPredicate: (day) {
          return isSameDay(_selectedDay, day);
        },
        onDaySelected: (selectedDay, focusedDay) {
          setState(() {
            _selectedDay = selectedDay;
            _focusedDay = focusedDay; // update `_focusedDay` here as well
            XLogger.getLogger().d('您选择的日期:$_selectedDay, 当前焦点日期:$_focusedDay');
          });
        },
        onFormatChanged: (format) {
          setState(() {
            _calendarFormat = format;
            XLogger.getLogger().d('当前日历格式:$_calendarFormat');
          });
        },
        onPageChanged: (focusedDay) {
          _focusedDay = focusedDay;
          XLogger.getLogger().d('当前焦点日期:$_focusedDay');
        },
      ),
    );
  }
}

3.效果

image