You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter移动端集成Google日历:新手开发团队的技术问询

Hey James, totally get the frustration with beta tools and sparse docs—been there with Flutter and Google's APIs before! Let's break down how to get your Google Calendar content showing up in your app step by step.

Step 1: Set Up Google Authentication

First, you'll need to let users sign in with their Google account and grant access to their calendars. We'll use two core packages here: google_sign_in for handling authentication, and googleapis to interact directly with the Calendar API.

  1. Add these dependencies to your pubspec.yaml:
dependencies:
  flutter:
    sdk: flutter
  google_sign_in: ^5.4.0
  googleapis: ^11.0.0
  googleapis_auth: ^1.4.0
  1. Initialize the Google Sign-In client with the required Calendar scope:
import 'package:google_sign_in/google_sign_in.dart';
import 'package:googleapis/calendar/v3.dart';
import 'package:googleapis_auth/googleapis_auth.dart';

final GoogleSignIn _googleSignIn = GoogleSignIn(
  scopes: [
    CalendarApi.calendarReadonlyScope, // Use `calendarScope` if you need write access later
  ],
);
  1. Implement the basic sign-in flow:
Future<void> _handleSignIn() async {
  try {
    await _googleSignIn.signIn();
    // Once signed in, trigger the event fetch
    _fetchCalendarEvents();
  } catch (error) {
    print('Sign-in error: $error');
  }
}

Don’t forget the critical setup in Google Cloud Console: enable the Calendar API, configure an OAuth consent screen, and add your Flutter app’s SHA-1 fingerprint (for Android) or bundle ID (for iOS) to your OAuth credentials.

Step 2: Fetch Calendar Events

With a signed-in user, you can get an authenticated HTTP client to call the Calendar API and pull events:

List<Event> _calendarEvents = [];

Future<void> _fetchCalendarEvents() async {
  final GoogleSignInAccount? account = _googleSignIn.currentUser;
  if (account == null) return;

  final AuthClient client = await account.authenticatedClient();
  final CalendarApi calendarApi = CalendarApi(client);

  try {
    final Events events = await calendarApi.events.list(
      'primary', // Target the user's primary calendar; replace with a specific calendar ID if needed
      maxResults: 10, // Adjust the number of events to fetch
      singleEvents: true,
      orderBy: 'startTime',
      timeMin: DateTime.now(), // Only fetch future events
    );

    final List<Event>? items = events.items;
    if (items != null && items.isNotEmpty) {
      setState(() {
        _calendarEvents = items;
      });
    }
  } catch (error) {
    print('Error fetching events: $error');
  }
}

A quick note: since the Dart Google API is in beta, keep an eye on the package’s release notes—occasionally method names or parameters might shift slightly.

Step 3: Display the Calendar Content

Now you can render the events using Flutter’s built-in widgets, or use a dedicated calendar package for a more interactive view.

Option 1: Simple List View

A straightforward way to list events:

@override
Widget build(BuildContext context) {
  return Scaffold(
    appBar: AppBar(title: const Text('My Google Calendar')),
    body: _calendarEvents.isEmpty
        ? const Center(child: Text('No upcoming events'))
        : ListView.builder(
            itemCount: _calendarEvents.length,
            itemBuilder: (context, index) {
              final Event event = _calendarEvents[index];
              // Handle both timed and all-day events
              final String startTime = event.start!.dateTime != null
                  ? '${event.start!.dateTime!.toLocal().toString().split(' ')[0]} ${event.start!.dateTime!.toLocal().toString().split(' ')[1].substring(0,5)}'
                  : event.start!.date!;

              return ListTile(
                title: Text(event.summary ?? 'Untitled Event'),
                subtitle: Text(startTime),
              );
            },
          ),
    floatingActionButton: FloatingActionButton(
      onPressed: _handleSignIn,
      child: const Icon(Icons.login),
    ),
  );
}

Option 2: Interactive Calendar Widget

For a more visual, date-based view, use packages like table_calendar or syncfusion_flutter_calendar. These let users tap dates to view associated events and integrate smoothly with the Event objects you fetched.

Just a heads-up: since both Flutter and the Dart Google API are in beta, you might hit minor bugs or missing features. Testing on both Android and iOS is key, and don’t hesitate to check the package’s GitHub issues for workarounds if you run into snags.

内容的提问来源于stack exchange,提问作者James Cory

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 10:03:41