Flutter Google API客户端插件googleapis_client的使用

发布于 1周前 作者 htzhanglong 来自 Flutter

Flutter Google API客户端插件googleapis_client的使用

googleapis_client 被创建是为了简化使用 Google APIs 的过程,尤其是对于新手或初学者来说。官方库可能较为复杂。


创建Secret API Key

  1. Service Account
    • 打开你的浏览器并访问 https://console.cloud.google.com
    • 创建一个项目或选择一个现有的项目
    • 打开“API 与服务”选项卡
    • 点击“创建凭据”
    • 选择“服务账号”

详细步骤请参见以下视频:

创建服务账号


安装库

pubspec.yaml 文件中添加以下依赖:

dart pub add googleapis_client

添加库

在 Dart 文件中导入库:

import 'package:googleapis_client/googleapis_client.dart';

文档

如果你没有足够的网络流量,可以使用以下命令下载文档:

git clone https://github.com/azkadev/googleapis_client.git
cd googleapis_client
cd web
flutter clean
flutter pub get
flutter run

快速开始

以下是一个简单的示例,展示如何使用 googleapis_client 库来调用 YouTube 和 Gmail API:

import 'dart:convert';
import 'package:googleapis_client/googleapis_client.dart';

void prettyPrint(dynamic data) {
  if (data is Map || data is List) {
    print(JsonEncoder.withIndent("  ").convert(data));
  } else {
    print(data.toString());
  }
}

void main(List<String> args) async { 
  GoogleApisClient googleApisClient = GoogleApisClient(
    googleApisClientApiKey: GoogleApisClientApiKey(
      {
        "type": "service_account",
        "project_id": "nod",
        "private_key_id": "",
        "private_key": "-----BEGIN -----END PRIVATE KEY-----\n",
        "client_email": "mkkm",
        "client_id": "1580",
        "auth_uri": "https://o/oauth2/auth",
        "token_uri": "https:/token",
        "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
        "client_x509_cert_url": "",
        "universe_domain": "",
      },
    ),
  );

  await googleApisClient.youtube.subscribeChannel(channel: "@azkadev");
  await googleApisClient.youtube.addComment(videoId: "HV4kn5j7IwQ", text: "Hai ini pesan automatis");

  // 使用 Dart 类模式
  await googleApisClient.request(
    requestData: YoutubeGetChannel.create(
      special_type: "youtubeGetChannel",
      channel_id: "@azkadev",
    ),
  );
  // 使用 Dart 类模式
  await googleApisClient.request(
    requestData: JsonApis({
      "@type": "youtubeSubscribeChannel",
      "@client_channel": "",
      "channel_id": "@azkadev",
    }),
  );

  await googleApisClient.request(
    requestData: JsonApis({
      "@type": "gmailSendMessage",
      "email_id": "email@gmail.com",
      "text": "",
    }),
  );
}

示例客户端使用此库

以下是一个完整的示例,展示了如何在 Flutter 应用程序中使用 googleapis_client 库:

import 'package:flutter/material.dart';
import 'package:googleapis_client/googleapis_client.dart';

void main() {
  GoogleApisClient googleApisClient = GoogleApisClient(googleApisClientApiKey: GoogleApisClientApiKey({}));
  googleApisClient;
  runApp(const MyApp());
}

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

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  [@override](/user/override)
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Text('You have pushed the button this many times:'),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headlineMedium,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ),
    );
  }
}

更多关于Flutter Google API客户端插件googleapis_client的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter Google API客户端插件googleapis_client的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,我可以为你提供一个关于如何在Flutter中使用googleapis_client插件的示例代码。googleapis_client插件允许你直接在Flutter应用中调用Google API。下面是一个简单的示例,展示如何设置并使用Google Calendar API。

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

dependencies:
  flutter:
    sdk: flutter
  googleapis_client: ^x.y.z  # 请替换为最新版本号

然后,运行flutter pub get来安装依赖。

1. 配置Google API

在使用Google API之前,你需要在Google Cloud Console中创建一个项目,并启用所需的API(例如Google Calendar API)。然后,创建一个OAuth 2.0客户端ID,并下载生成的credentials.json文件。

2. 设置Flutter项目

credentials.json文件放到你的Flutter项目的android/app目录下。

3. 使用googleapis_client

以下是一个简单的示例代码,展示如何在Flutter中使用googleapis_client调用Google Calendar API来列出用户的日历事件:

import 'package:flutter/material.dart';
import 'package:googleapis_client/googleapis_client.dart';
import 'dart:convert' as convert;

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Google Calendar API Example'),
        ),
        body: Center(
          child: CalendarEvents(),
        ),
      ),
    );
  }
}

class CalendarEvents extends StatefulWidget {
  @override
  _CalendarEventsState createState() => _CalendarEventsState();
}

class _CalendarEventsState extends State<CalendarEvents> {
  List<dynamic> events = [];

  @override
  void initState() {
    super.initState();
    _fetchCalendarEvents();
  }

  Future<void> _fetchCalendarEvents() async {
    // 读取credentials.json文件
    final String credentialsPath = 'android/app/credentials.json';
    final File credentialsFile = File(credentialsPath);
    final String credentialsContent = await credentialsFile.readAsString();

    // 创建Google API客户端
    final GoogleAuth googleAuth = GoogleAuth(
      scopes: ['https://www.googleapis.com/auth/calendar.readonly'],
      clientId: convert.jsonDecode(credentialsContent)['installed']['client_id'],
      clientSecret: convert.jsonDecode(credentialsContent)['installed']['client_secret'],
      redirectUri: convert.jsonDecode(credentialsContent)['installed']['redirect_uris'][0],
    );

    // 获取访问令牌
    final String accessToken = await googleAuth.requestAccessToken();

    // 配置HTTP客户端
    final http.Client httpClient = http.Client();
    final String url = 'https://www.googleapis.com/calendar/v3/events';
    final String calendarId = 'primary'; // 可以替换为具体的日历ID
    final String requestBody = '{"timeMin": "2023-10-01T00:00:00.000Z", "timeMax": "2023-10-31T00:00:00.000Z", "singleEvents": true, "orderBy": "startTime", "maxResults": 10}';

    final http.Request request = http.Request('POST', Uri.parse(url))
      ..headers.addAll({
        'Content-Type': 'application/json',
        'Authorization': 'Bearer $accessToken',
      })
      ..body = convert.utf8.encode(requestBody);

    final http.Response response = await httpClient.send(request);

    if (response.statusCode == 200) {
      final String responseBody = await response.body.decodeString();
      setState(() {
        events = convert.jsonDecode(responseBody)['items'];
      });
    } else {
      print('Failed to fetch calendar events: ${response.statusCode}');
    }

    httpClient.close();
  }

  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      itemCount: events.length,
      itemBuilder: (context, index) {
        final event = events[index];
        return ListTile(
          title: Text(event['summary']),
          subtitle: Text(event['start']['dateTime'] ?? event['start']['date']),
        );
      },
    );
  }
}

注意事项

  1. 权限问题:确保在AndroidManifest.xmlInfo.plist文件中添加了必要的权限,以允许应用访问网络。
  2. 错误处理:示例代码中没有包含详细的错误处理逻辑,实际开发中应该添加适当的错误处理。
  3. 安全性:将credentials.json文件放在android/app目录下仅适用于开发阶段。在生产环境中,建议使用更安全的方式来管理凭据。

这个示例展示了如何读取credentials.json文件,获取访问令牌,并使用Google Calendar API来列出用户的事件。你可以根据需要修改代码来调用其他Google API。

回到顶部