惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

J
Java Code Geeks
IT之家
IT之家
爱范儿
爱范儿
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
博客园_首页
Blog — PlanetScale
Blog — PlanetScale
V
Visual Studio Blog
云风的 BLOG
云风的 BLOG
MyScale Blog
MyScale Blog
阮一峰的网络日志
阮一峰的网络日志
Stack Overflow Blog
Stack Overflow Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
GbyAI
GbyAI
V
V2EX
N
Netflix TechBlog - Medium
Vercel News
Vercel News
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
T
The Blog of Author Tim Ferriss
量子位
博客园 - Franky
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
博客园 - 司徒正美
月光博客
月光博客
F
Fortinet All Blogs

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
How to Fetch Apple Calendar Events and Reminders in Flutt...
Codexlancers · 2026-06-19 · via DEV Community
Cover image for How to Fetch Apple Calendar Events and Reminders in Flutter (macOS)

Codexlancers

Building a macOS app with Flutter and need access to Apple Calendar events and Reminders? Flutter cannot directly access EventKit (Apple's framework for calendars and reminders), so we bridge using native Swift and MethodChannels.
In this guide, we'll build a complete pipeline that even a beginner can follow.

1. Understanding the Architecture

Flutter macOS Calendar Integration

Flutter side (Dart):

Sends a method name and optional arguments to Swift.
Example: "fetchCalendarEvents" with a list of calendar IDs.

Swift side:

Checks which method Flutter called (call.method).
Does the EventKit work (fetch events or reminders).
Sends the results back to Flutter using result(...).

Important:

Flutter can only understand simple data from Swift:

  • Strings, numbers, booleans, lists, maps.
  • No custom objects or raw Date objects.
  • Convert Date to a string in ISO8601 format first.

Permissions:

  • macOS asks the user only once for calendar/reminder access.
  • First time: a system dialog appears.
  • After that, macOS remembers the choice until the user changes it manually in System Settings → Privacy

2. macOS Project Setup

a) Add Entitlements

Open:

  • macos/Runner/DebugProfile.entitlements
  • macos/Runner/Release.entitlements

Add inside <dict>:

<key>com.apple.security.personal-information.calendars</key>
<true/>
<key>com.apple.security.personal-information.reminders</key>
<true/>

b) Update Info.plist

Add usage descriptions:

<key>NSCalendarsFullAccessUsageDescription</key>
<string>This app needs access to your calendar.</string>
<key>NSRemindersFullAccessUsageDescription</key>
<string>This app needs access to your reminders.</string>

<!-- For macOS 13 or older -->
<key>NSCalendarsUsageDescription</key>
<string>This app needs access to your calendar.</string>
<key>NSRemindersUsageDescription</key>
<string>This app needs access to your reminders.</string>

3. Native Swift Implementation

a) Create CalendarBridge.swift

import Cocoa
import EventKit

@objc class CalendarBridge: NSObject {

    // Use a single shared EKEventStore for the whole app
    static let store = EKEventStore()

    // MARK: - Permission Requests

    /// Request calendar access permission from the user
    @objc static func requestCalendarPermission(_ result: @escaping (Bool) -> Void) {
        if #available(macOS 14.0, *) {
            store.requestFullAccessToEvents { granted, _ in
                if granted { store.reset() } // Refresh calendars after permission
                DispatchQueue.main.async { result(granted) }
            }
        } else {
            store.requestAccess(to: .event) { granted, _ in
                if granted { store.reset() }
                DispatchQueue.main.async { result(granted) }
            }
        }
    }

    /// Request reminders access permission from the user
    @objc static func requestReminderPermission(_ result: @escaping (Bool) -> Void) {
        if #available(macOS 14.0, *) {
            store.requestFullAccessToReminders { granted, _ in
                if granted { store.reset() }
                DispatchQueue.main.async { result(granted) }
            }
        } else {
            store.requestAccess(to: .reminder) { granted, _ in
                if granted { store.reset() }
                DispatchQueue.main.async { result(granted) }
            }
        }
    }

    // MARK: - Authorization Check

    /// Check if calendar access is already authorized
    @objc static func isCalendarAuthorized() -> Bool {
        switch EKEventStore.authorizationStatus(for: .event) {
        case .authorized, .fullAccess:
            return true
        default:
            return false
        }
    }

    // MARK: - Calendars

    /// Get all available calendars for events
    @objc static func getCalendars() -> [[String: String]] {
        let calendars = store.calendars(for: .event)
        return calendars.map { cal in
            let source = cal.source.sourceType == .local ? "Default" : cal.source.title
            return [
                "id": cal.calendarIdentifier,
                "title": cal.title,
                "sourceType": source,
                "sourceTitle": cal.source.title
            ]
        }
    }

    /// Fetch events from the selected calendar IDs for the next 7 days
    @objc static func fetchEvents(calendarIds: [String], result: @escaping ([[String: Any]]) -> Void) {
        guard isCalendarAuthorized() else {
            result([["error": "permission_denied"]])
            return
        }

        let calendars = store.calendars(for: .event).filter { calendarIds.contains($0.calendarIdentifier) }
        let now = Date()
        let weekAhead = Calendar.current.date(byAdding: .day, value: 7, to: now)!

        let isoFormatter = ISO8601DateFormatter()
        isoFormatter.formatOptions = [.withInternetDateTime]

        var events: [[String: Any]] = []

        for cal in calendars {
            let predicate = store.predicateForEvents(withStart: now, end: weekAhead, calendars: [cal])
            for event in store.events(matching: predicate) {
                events.append([
                    "id": event.eventIdentifier ?? "",
                    "title": event.title ?? "No Title",
                    "start": isoFormatter.string(from: event.startDate),
                    "end": isoFormatter.string(from: event.endDate),
                    "location": event.location ?? "",
                    "notes": event.notes ?? "",
                    "isAllDay": event.isAllDay,
                    "calendarId": event.calendar.calendarIdentifier,
                    "calendarTitle": event.calendar.title
                ])
            }
        }

        result(events)
    }

    // MARK: - Reminders

    /// Get all reminder lists
    @objc static func getReminderLists() -> [[String: String]] {
        store.reset() // Refresh lists after permission granted
        return store.calendars(for: .reminder).map { cal in
            let source = cal.source.sourceType == .local ? "Default" : cal.source.title
            return [
                "id": cal.calendarIdentifier,
                "title": cal.title,
                "sourceType": source
            ]
        }
    }

    /// Fetch all reminders in a specific list
    @objc static func fetchReminders(listId: String, result: @escaping ([[String: Any]]) -> Void) {
        let lists = store.calendars(for: .reminder)
        guard let list = lists.first(where: { $0.calendarIdentifier == listId }) else {
            result([["error": "list_not_found"]])
            return
        }

        let isoFormatter = ISO8601DateFormatter()
        isoFormatter.formatOptions = [.withInternetDateTime]

        let predicate = store.predicateForReminders(in: [list])
        store.fetchReminders(matching: predicate) { reminders in
            let mapped = (reminders ?? []).map { r -> [String: Any] in
                let dueDate = r.dueDateComponents?.date.map { isoFormatter.string(from: $0) } ?? ""
                return [
                    "id": r.calendarItemIdentifier,
                    "title": r.title ?? "No Title",
                    "notes": r.notes ?? "",
                    "completed": r.isCompleted,
                    "dueDate": dueDate,
                    "hasDueDate": r.dueDateComponents != nil,
                    "priority": r.priority
                ]
            }
            result(mapped)
        }
    }
}

b) Wire it up in AppDelegate.swift

import Cocoa
import FlutterMacOS
import EventKit

@main
class AppDelegate: FlutterAppDelegate {
    private var channel: FlutterMethodChannel?

    override func applicationDidFinishLaunching(_ notification: Notification) {
        let controller = NSApplication.shared.windows.first!.contentViewController as! FlutterViewController
        channel = FlutterMethodChannel(name: "method_macos_native", binaryMessenger: controller.engine.binaryMessenger)

        channel!.setMethodCallHandler { call, result in
            switch call.method {
            case "requestCalendarPermission":
                CalendarBridge.requestCalendarPermission { granted in result(granted) }
            case "requestReminderPermission":
                CalendarBridge.requestReminderPermission { granted in result(granted) }
            case "checkCalendarPermission":
                result(CalendarBridge.isCalendarAuthorized())
            case "getCalendars":
                result(CalendarBridge.getCalendars())
            case "fetchCalendarEvents":
                let ids = (call.arguments as? [String: Any])?["calendarIds"] as? [String] ?? []
                DispatchQueue.global().async {
                    CalendarBridge.fetchEvents(calendarIds: ids) { events in
                        DispatchQueue.main.async { result(events) }
                    }
                }
            case "getReminderLists":
                DispatchQueue.global().async {
                    let lists = CalendarBridge.getReminderLists()
                    DispatchQueue.main.async { result(lists) }
                }
            case "fetchReminders":
                let listId = (call.arguments as? [String: Any])?["listId"] as? String ?? ""
                DispatchQueue.global().async {
                    CalendarBridge.fetchReminders(listId: listId) { reminders in
                        DispatchQueue.main.async { result(reminders) }
                    }
                }
            default:
                result(FlutterMethodNotImplemented)
            }
        }

        setupCalendarChangeObserver()
        super.applicationDidFinishLaunching(notification)
    }

    private func setupCalendarChangeObserver() {
        NotificationCenter.default.addObserver(forName: .EKEventStoreChanged,
                                               object: CalendarBridge.store,
                                               queue: .main) { [weak self] _ in
            self?.channel?.invokeMethod("onCalendarChanged", arguments: nil)
        }
    }
}

4. Flutter (Dart) Side - CalendarService

Create lib/services/calendar_service.dart:

import 'dart:io';
import 'package:flutter/services.dart';

class CalendarService {
  static const MethodChannel _channel = MethodChannel('method_macos_native');

  static Future<bool> requestCalendarPermission() async { ... }
  static Future<bool> requestReminderPermission() async { ... }
  static Future<List<Map<String, dynamic>>> getCalendars() async { ... }
  static Future<List<Map<String, dynamic>>> fetchEvents(List<String> calendarIds) async { ... }
  static Future<List<Map<String, dynamic>>> getReminderLists() async { ... }
  static Future<List<Map<String, dynamic>>> fetchReminders(String listId) async { ... }
}

5. Calling From UI

Future<void> loadCalendar() async {
  final granted = await CalendarService.requestCalendarPermission();
  if (!granted) return;
  final calendars = await CalendarService.getCalendars();
  final ids = calendars.map((c) => c['id'] as String).toList();
  final events = await CalendarService.fetchEvents(ids);
  events.forEach((e) => print('${e['title']} @ ${e['start']}'));
}

Future<void> loadReminders() async {
  if (!await CalendarService.requestReminderPermission()) return;
  final lists = await CalendarService.getReminderLists();
  for (final list in lists) {
    final reminders = await CalendarService.fetchReminders(list['id'] as String);
    print('${list['title']}: ${reminders.length} reminders');
  }
}

6. Fetching Reminders In Depth

  • Reminder Lists = EKCalendar of type .reminder.
  • Each reminder = EKReminder.
  • Permissions are separate from calendars.
  • Fetch asynchronously using store.fetchReminders.
final lists = await CalendarService.getReminderLists();
for (final list in lists) {
  final all = await CalendarService.fetchReminders(list['id'] as String);
  final open = all.where((r) => r['completed'] != true).toList();
  print('- ${list['title']} (${open.length} open) -');
}

7. Live Updates

EventKit fires .EKEventStoreChanged for any changes. In Flutter:

void listenForCalendarChanges(VoidCallback onChanged) {
  const channel = MethodChannel('method_macos_native');
  channel.setMethodCallHandler((call) async {
    if (call.method == 'onCalendarChanged') onChanged();
  });
}

8. Things to Watch Out For

Empty results after permission

If you just gave access, sometimes calendars/reminders show empty.
Fix: Use only one shared EKEventStore for the whole app.

Reminders fetch is asynchronous

Fetching reminders does not happen instantly.
Fix: Always return the data to Flutter inside the completion block.

macOS 14+ API changes

New versions of macOS use requestFullAccessToEvents and requestFullAccessToReminders.
Old methods may not work correctly.

Dates must be strings

You cannot send Date objects directly to Flutter.
Fix: Convert dates to ISO8601 strings using ISO8601DateFormatter.

Channel or method name typos

If names don't match exactly between Flutter and Swift, nothing will work and there's no error.
Double-check spelling and capitalization.

Entitlements in Debug and Release

You must add calendar/reminder entitlements in both Debug and Release files.
Otherwise, it may work in release but not during testing.

Heavy fetches on main thread

Fetching a lot of events can freeze your app.
Fix: Do heavy work on a background thread, not the main UI thread.