Flutter日历管理插件calendar_cc的使用

Flutter日历管理插件calendar_cc的使用

calendar_cc 是一个基于 flutter_neat_and_clean_calendar 包的简单 Flutter 日历组件。以下是其功能和使用方法。

功能

该日历视图显示所选日期的事件列表,并支持自定义日期生成器。此列表视图支持以下三种类型的事件:

  • 单日事件(在某一天的特定时间开始和结束)
  • 全天事件(跨越一整天,没有特定的开始和结束时间,属性为 isAllDay
  • 多日事件(从某一天的特定时间开始,在另一天的特定时间结束,属性为 isMultiDay
  • 禁用某些月份的特定日期作为假日
  • 阻止某些日期

开始使用

Calendar 小部件嵌入到列中。在日历下方(作为列中的第二个小部件)放置一个 ListView.separated 小部件以渲染事件列表。

设置依赖项

dependencies:
  calendar_cc: ^0.0.1

安装

flutter pub get

导入

import 'package:calendar_cc/calendar.dart';

使用

Calendar(
    eventsList: eventList,
    isExpandable: false,
    eventColor: null,
    isExpanded: true,
    todayColor: Colors.teal,
    selectedColor: Colors.blue,
    defaultDayColor: Colors.black,
    selectedTodayColor: Colors.green,
    datePickerType: DatePickerType.date,
    eventDoneColor: Colors.deepPurple,
    defaultOutOfMonthDayColor: Colors.grey,
    expandableDateFormat: 'EEEE, dd. MMMM yyyy',
    onEventSelected: (value) {
        debugPrint('Event selected ${value.summary}');
    },
    onEventLongPressed: (value) {
        debugPrint('Event long pressed ${value.summary}');
    },
    onDateSelected: (value) {
        debugPrint('Date selected $value');
    },
    onRangeSelected: (value) {
        debugPrint('Range selected ${value.from} - ${value.to}');
    },
    dayOfWeekStyle: const TextStyle(
        color: Colors.red,
        fontWeight: FontWeight.w800,
        fontSize: 11,
    ),
)

完整示例

import 'package:flutter/material.dart';
import 'package:calendar_cc/enums.dart';
import 'package:calendar_cc/calendar.dart';

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

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

  // 这是您的应用的根小部件。
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: '日历CC演示',
      theme: ThemeData.light(),
      darkTheme: ThemeData.dark(),
      themeMode: ThemeMode.system,
      home: const CalendarScreen(),
      debugShowCheckedModeBanner: false,
    );
  }
}

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

  [@override](/user/override)
  State<CalendarScreen> createState() => _CalendarScreenState();
}

class _CalendarScreenState extends State<CalendarScreen> {
  bool showEvents = true;

  final List<FlutterCalenderEvent> todaysEvents = [
    FlutterCalenderEvent(
      'Event A',
      startTime: DateTime(
          DateTime.now().year, DateTime.now().month, DateTime.now().day, 10, 0),
      endTime: DateTime(
          DateTime.now().year, DateTime.now().month, DateTime.now().day, 12, 0),
      description: 'A special event',
      color: Colors.blue[700],
    ),
  ];

  final List<FlutterCalenderEvent> eventList = [
    FlutterCalenderEvent(
      'MultiDay Event A',
      description: 'test desc',
      startTime: DateTime(
          DateTime.now().year, DateTime.now().month, DateTime.now().day, 10, 0),
      endTime: DateTime(DateTime.now().year, DateTime.now().month,
          DateTime.now().day + 2, 12, 0),
      color: Colors.orange,
      isMultiDay: true,
    ),
    FlutterCalenderEvent(
      'Event X',
      description: 'test desc',
      startTime: DateTime(DateTime.now().year, DateTime.now().month,
          DateTime.now().day, 10, 30),
      endTime: DateTime(DateTime.now().year, DateTime.now().month,
          DateTime.now().day, 11, 30),
      color: Colors.lightGreen,
      isAllDay: false,
      isDone: true,
    ),
    FlutterCalenderEvent(
      'Allday Event B',
      description: 'test desc',
      startTime: DateTime(DateTime.now().year, DateTime.now().month,
          DateTime.now().day - 2, 14, 30),
      endTime: DateTime(DateTime.now().year, DateTime.now().month,
          DateTime.now().day + 2, 17, 0),
      color: Colors.pink,
      isAllDay: true,
    ),
    FlutterCalenderEvent(
      'Normal Event D',
      description: 'test desc',
      startTime: DateTime(DateTime.now().year, DateTime.now().month,
          DateTime.now().day, 14, 30),
      endTime: DateTime(
          DateTime.now().year, DateTime.now().month, DateTime.now().day, 17, 0),
      color: Colors.indigo,
    ),
    FlutterCalenderEvent(
      'Normal Event E',
      description: 'test desc',
      startTime: DateTime(
          DateTime.now().year, DateTime.now().month, DateTime.now().day, 7, 45),
      endTime: DateTime(
          DateTime.now().year, DateTime.now().month, DateTime.now().day, 9, 0),
      color: Colors.indigo,
    ),
  ];

  [@override](/user/override)
  void initState() {
    super.initState();
    // 强制选择今天,以便显示今天的事件列表。
    _handleNewDate(
      DateTime(DateTime.now().year, DateTime.now().month, DateTime.now().day),
    );
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: Calendar(
          eventsList: eventList,
          isExpandable: false,
          eventColor: null,
          isExpanded: true,
          todayColor: Colors.teal,
          selectedColor: Colors.blue,
          defaultDayColor: Colors.black,
          selectedTodayColor: Colors.green,
          datePickerType: DatePickerType.date,
          eventDoneColor: Colors.deepPurple,
          defaultOutOfMonthDayColor: Colors.grey,
          expandableDateFormat: 'EEEE, dd. MMMM yyyy',
          holidays: const [2, 4],
          blockedDates: [DateTime(DateTime.now().year, 11, 29)],
          onEventSelected: (value) {
            debugPrint('Event selected ${value.summary}');
          },
          onEventLongPressed: (value) {
            debugPrint('Event long pressed ${value.summary}');
          },
          onDateSelected: (value) {
            debugPrint('Date selected $value');
          },
          onRangeSelected: (value) {
            debugPrint('Range selected ${value.from} - ${value.to}');
          },
          dayOfWeekStyle: const TextStyle(
            color: Colors.red,
            fontWeight: FontWeight.w800,
            fontSize: 11,
          ),
        ),
      ),
    );
  }

  void _handleNewDate(date) {
    debugPrint('Date selected: $date');
  }
}

更多关于Flutter日历管理插件calendar_cc的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter日历管理插件calendar_cc的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


calendar_cc 是一个用于 Flutter 的日历管理插件,它可以帮助你在应用中集成日历功能,包括创建、读取、更新和删除日历事件。以下是如何在 Flutter 项目中使用 calendar_cc 插件的基本步骤。

1. 添加依赖

首先,你需要在 pubspec.yaml 文件中添加 calendar_cc 插件的依赖:

dependencies:
  flutter:
    sdk: flutter
  calendar_cc: ^1.0.0  # 请使用最新版本

然后运行 flutter pub get 来获取依赖。

2. 导入插件

在你的 Dart 文件中导入 calendar_cc 插件:

import 'package:calendar_cc/calendar_cc.dart';

3. 请求权限

在使用日历功能之前,你需要在 Android 和 iOS 上请求相应的权限。

Android

AndroidManifest.xml 中添加以下权限:

<uses-permission android:name="android.permission.READ_CALENDAR" />
<uses-permission android:name="android.permission.WRITE_CALENDAR" />

iOS

Info.plist 中添加以下键值对:

<key>NSCalendarsUsageDescription</key>
<string>We need access to your calendar to manage events.</string>

4. 使用 calendar_cc 插件

以下是一些常见的使用场景:

获取日历列表

List<Calendar> calendars = await CalendarCC.getCalendars();
for (var calendar in calendars) {
  print('Calendar Name: ${calendar.name}');
  print('Calendar ID: ${calendar.id}');
}

创建日历事件

Event event = Event(
  calendarId: calendars[0].id, // 使用第一个日历
  title: 'Meeting with Team',
  description: 'Discuss project updates',
  start: DateTime.now(),
  end: DateTime.now().add(Duration(hours: 1)),
  location: 'Office',
  allDay: false,
);

await CalendarCC.createEvent(event);

读取日历事件

List<Event> events = await CalendarCC.getEvents(
  calendarId: calendars[0].id,
  startDate: DateTime.now(),
  endDate: DateTime.now().add(Duration(days: 7)),
);

for (var event in events) {
  print('Event Title: ${event.title}');
  print('Event Start: ${event.start}');
  print('Event End: ${event.end}');
}

更新日历事件

Event updatedEvent = Event(
  id: events[0].id, // 使用第一个事件的ID
  calendarId: calendars[0].id,
  title: 'Updated Meeting with Team',
  description: 'Discuss project updates and new features',
  start: DateTime.now().add(Duration(days: 1)),
  end: DateTime.now().add(Duration(days: 1, hours: 1)),
  location: 'Conference Room',
  allDay: false,
);

await CalendarCC.updateEvent(updatedEvent);

删除日历事件

await CalendarCC.deleteEvent(events[0].id);

5. 处理权限

在使用日历功能之前,确保你已经获得了必要的权限。你可以使用 permission_handler 插件来请求权限:

import 'package:permission_handler/permission_handler.dart';

Future<void> requestCalendarPermissions() async {
  if (await Permission.calendar.request().isGranted) {
    // 权限已授予
  } else {
    // 权限被拒绝
  }
}

6. 处理错误

在使用 calendar_cc 插件时,可能会遇到各种错误,例如权限被拒绝、日历不存在等。确保你正确处理这些错误。

try {
  await CalendarCC.createEvent(event);
} catch (e) {
  print('Error creating event: $e');
}
回到顶部